Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array and objects in array to pure array [duplicate]

Tags:

arrays

php

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?

like image 826
Thompson Avatar asked May 17 '12 07:05

Thompson


People also ask

Which method is used to convert nested arrays to object?

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.

What array will you get if you convert an object to an array in PHP?

If an object is converted to an array, the result is an array whose elements are the object's properties.

How do you convert an object to an array?

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.

How do you convert an array to an object in mule 4?

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.


2 Answers

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)

like image 179
Ibrahim Azhar Armar Avatar answered Oct 14 '22 15:10

Ibrahim Azhar Armar


Just use this :

json_decode(json_encode($yourArray), true); 
like image 20
Mahdi Shad Avatar answered Oct 14 '22 17:10

Mahdi Shad