Home > Article > Backend Development > How to use recursion to convert PHP arrays and objects, array recursion_PHP tutorial
The example in this article describes the method of using recursion to achieve conversion between PHP arrays and objects. Share it with everyone for your reference. The specific implementation method is as follows:
This involves some simple conversion issues between objects and arrays. Two methods are written using recursion as follows:
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; }
function object_to_array($e) { $_arr = is_object($e) ? get_object_vars($e) : $e; foreach ($_arr as $key => $val) { $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val; $arr[$key] = $val; } return $arr; }
I hope this article will be helpful to everyone’s PHP programming design.