PHP - recursive Array to Object?

Peter picture Peter · Jan 25, 2011 · Viewed 36.1k times · Source

Is there a way to convert a multidimensional array to a stdClass object in PHP?

Casting as (object) doesn't seem to work recursively. json_decode(json_encode($array)) produces the result I'm looking for, but there has to be a better way...

Answer

Jacob Relkin picture Jacob Relkin · Jan 25, 2011

As far as I can tell, there is no prebuilt solution for this, so you can just roll your own:

function array_to_object($array) {
  $obj = new stdClass;
  foreach($array as $k => $v) {
     if(strlen($k)) {
        if(is_array($v)) {
           $obj->{$k} = array_to_object($v); //RECURSION
        } else {
           $obj->{$k} = $v;
        }
     }
  }
  return $obj;
}