Php simple object and array conversion function code (php multi-layer array and object conversion) functionarrayToObject ($ e) {if (gettype ($ e )! = 'Array') return; foreach ($ eas $ k = & gt; $ v) {if (gettype ($ v) = 'array' php simple object and array conversion function code (php multi-layer array and object conversion)
function arrayToObject($e){ if( gettype($e)!='array' ) return; foreach($e as $k=>$v){ if( gettype($v)=='array' || getType($v)=='object' ) $e[$k]=(object)arrayToObject($v); } return (object)$e; } function objectToArray($e){ $e=(array)$e; foreach($e as $k=>$v){ if( gettype($v)=='resource' ) return; if( gettype($v)=='object' || gettype($v)=='array' ) $e[$k]=(array)objectToArray($v); } return $e; }
Php multi-layer array and object conversion
Multi-layer arrays and object conversion are easy to use, making it easy to process multi-layer arrays and object conversion in WebService.
Simple (array) and (object) can only process single-layer data, but there is nothing to do with multi-layer array and object conversion.
Json_decode (json_encode ($ object) can be used to convert an object to an array at a time. However, problems may occur when the object encounters non-UTF-8 encoded non-ascii characters, such as gbk Chinese characters, besides, the performance of json_encode and decode is also worth considering.
foo = "Test data"; $init->bar = new stdClass; $init->bar->baaz = "Testing"; $init->bar->fooz = new stdClass; $init->bar->fooz->baz = "Testing again"; $init->foox = "Just test"; // Convert array to object and then object back to array $array = objectToArray($init); $object = arrayToObject($array); // Print objects and array print_r($init); echo "\n"; print_r($array); echo "\n"; print_r($object); ?>