Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdClass to array?

Tags:

i have:

stdClass Object (     [0] => stdClass Object         (             [one] => aaa             [two] => sss         )      [1] => stdClass Object         (             [one] => ddd             [two] => fff         )      [2] => stdClass Object         (             [one] => ggg             [two] => hhh         ) } 

and i must get this with keys, for example:

$var = $stdClass[0];  

but i have error:

Fatal error: Cannot use object of type stdClass as array in

Is possible parse this stdClass to array and use this with keys?

like image 468
Lucci Fangorci Avatar asked Jul 09 '12 13:07

Lucci Fangorci


People also ask

What is stdClass?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How do I print a stdClass object?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .


2 Answers

Cast it to an array:

$array = (array)$stdClass; 
like image 174
deceze Avatar answered Oct 01 '22 11:10

deceze


If you're using json_decode to convert that JSON string into an object, you can use the second parameter json_decode($string, true) and that will convert the object to an associative array.

If not, what everybody else has said and just type cast it

$array = (array) $stdClass;

like image 42
Marcus Recck Avatar answered Oct 01 '22 10:10

Marcus Recck