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...
As far as I can tell, there is no prebuilt solution for this, so you can just roll your own:
Here's a function to do an in-place deep array-to-object conversion that uses PHP internal (shallow) array-to-object type casting mechanism. It creates new objects only when necessary, minimizing data duplication.
Warning - do not use this code if there is a risk of having circular references.
You can use the
array_map
recursively:Works perfect for me since it doesn't cast for example Carbon objects to a basic stdClass (which the json encode/decode does)
EDIT: This function is conversion from object to array.
From https://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka
The shortest I could come up with: