My array is like:
Array ( [0] => stdClass Object ( [id] => 1 [name] => demo1 ) [1] => stdClass Object ( [id] => 2 [name] => demo2 ) [2] => stdClass Object ( [id] => 6 [name] => otherdemo ) )
How can I convert the whole array (including objects) to a pure multi-dimensional array?
You can use map to iterate over the subarrays in your main array and then use reduce to convert their child arrays to object properties.
If an object is converted to an array, the result is an array whose elements are the object's properties.
To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.
You can use the reduce() function to transform an array into an object. Each element of the array into is transformed into an object (key-value pairs) and then is concatenated in the accumulator so all key-pairs are joined into a single object.
Have you tried typecasting?
$array = (array) $object;
There is another trick actually
$json = json_encode($object); $array = json_decode($json, true);
You can have more info here json_decode
in the PHP manual, the second parameter is called assoc:
assoc
When
TRUE
, returned objects will be converted into associative arrays.
Which is exactly what you're looking for.
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
Just use this :
json_decode(json_encode($yourArray), true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With