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...
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...
Here is a smooth way to do it that can handle an associative array with great depth and doesn't overwrite object properties that are not in the array.
Some of the other solutions posted here fail to tell apart sequential arrays (what would be
[]
in JS) from maps ({}
in JS.) For many use cases it's important to tell apart PHP arrays that have all sequential numeric keys, which should be left as such, from PHP arrays that have no numeric keys, which should be converted to objects. (My solutions below are undefined for arrays that don't fall in the above two categories.)The
json_decode(json_encode($x))
method does handle the two types correctly, but is not the fastest solution. It's still decent though, totaling 25µs per run on my sample data (averaged over 1M runs, minus the loop overhead.)I benchmarked a couple of variations of the recursive converter and ended up with the following. It rebuilds all arrays and objects (performing a deep copy) but seems to be faster than alternative solutions that modify the arrays in place. It clocks at 11µs per execution on my sample data:
Here is an in-place version. It may be faster on some large input data where only small parts need to be converted, but on my sample data it took 15µs per execution:
I did not try out solutions using
array_walk_recursive()