<BR>function arrayToObject($e){ <BR>if( gettype($e)!='array' ) return; <BR>foreach($e as $k=>$v){ <BR>if( gettype($v)=='array' || getType($v)=='object' ) <BR>$e[$k]=(object)arrayToObject($v); <BR>} <BR>return (object)$e; <BR>} <br><br>function objectToArray($e){ <BR>$e=(array)$e; <BR>foreach($e as $k=>$v){ <BR>if( gettype($v)=='resource' ) return; <BR>if( gettype($v)=='object' || gettype($v)=='array' ) <BR>$e[$k]=(array)<p style="color:transparent">。本文来源gao!%daima.com搞$代*!码网1</p><cite>搞代gaodaima码</cite>objectToArray($v); <BR>} <BR>return $e; <BR>} <BR>
上面的内容来自 cnblogs jaiho
php多层数组和对象的转换
多层数组和对象转化的用途很简单,便于处理WebService中多层数组和对象的转化
简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。
下面上代码:
<BR><?php <br><br>function objectToArray($d) { <BR>if (is_object($d)) { <BR>// Gets the properties of the given object <BR>// with get_object_vars function <BR>$d = get_object_vars($d); <BR>} <br><br>if (is_array($d)) { <BR>/* <BR>* Return array converted to object <BR>* Using __FUNCTION__ (Magic constant) <BR>* for recursive call <BR>*/ <BR>return array_map(__FUNCTION__, $d); <BR>} <BR>else { <BR>// Return array <BR>return $d; <BR>} <BR>} <br><br>function arrayToObject($d) { <BR>if (is_array($d)) { <BR>/* <BR>* Return array converted to object <BR>* Using __FUNCTION__ (Magic constant) <BR>* for recursive call <BR>*/ <BR>return (object) array_map(__FUNCTION__, $d); <BR>} <BR>else { <BR>// Return object <BR>return $d; <BR>} <BR>} <br><br>// Useage: <BR>// Create new stdClass Object <BR>$init = new stdClass; <BR>// Add some test data <BR>$init->foo = "Test data"; <BR>$init->bar = new stdClass; <BR>$init->bar->baaz = "Testing"; <BR>$init->bar->fooz = new stdClass; <BR>$init->bar->fooz->baz = "Testing again"; <BR>$init->foox = "Just test"; <br><br>// Convert array to object and then object back to array <BR>$array = objectToArray($init); <BR>$object = arrayToObject($array); <br><br>// Print objects and array <BR>print_r($init); <BR>echo "\n"; <BR>print_r($array); <BR>echo "\n"; <BR>print_r($object); <BR>?> <BR>