up vote 5 down vote favorite
share [fb]

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...

link|improve this question

feedback

2 Answers

up vote 13 down vote accepted

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(is_array($v)) {
        $obj->{$k} = array_to_object($v); //RECURSION
     } else {
        $obj->{$k} = $v;
     }
  }
  return $obj;
} 
link|improve this answer
feedback
function toObject($array) {
    $obj = new stdClass();
    foreach ($array as $key => $val) {
        $obj->$key = is_array($val) ? toObject($val) : $val;
    }
    return $obj;
}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.