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...
I know this answer is coming late but I'll post it for anyone who's looking for a solution.
Instead of all this looping etc, you can use PHP's native json_* function. I've got a couple of handy functions that I use a lot
Hope this can be helpful
Late, but just wanted to mention that you can use the JSON encoding/decoding to convert fully from/to array:
json_encode and json_decode functions are available starting from php 5.2
You and many others have pointed to the JSON built-in functions,
json_decode()
andjson_encode()
. The method which you have mentioned works, but not completely: it won't convert indexed arrays to objects, and they will remain as indexed arrays. However, there is a trick to overcome this problem. You can useJSON_FORCE_OBJECT
constant:Tip: Also, as mentioned here, you can convert an object to array recursively using JSON functions:
The simpliest way to convert an associative array to object is:
First encode it in json, then decode it.
like
$objectArray = json_decode(json_encode($associtiveArray));