If Not True Then False

PHP stdClass to Array and Array to stdClass – stdClass Object - Comment Page: 4

I think every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects. This post defines two ultra simple recursive function to convert...
Categories:
Tagged with:

59 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Input your comment.
help

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Input your name.

Goga

Your post is very helpful, Thank’s! Could you please change a website’s font. I have broken my eyes

reply Reply
Alaa M. Jaddou

hey dear,

sorry but you can use casting in php it’s easier
$object = (object) $array;
// now $object has array elements as object;

$array = (array) $object;
// now $array has everything in $object as an array

and thanks for listening :D

reply Reply
JR

Hi Alaa M. Jaddou,

Try following:


php -r '$object = (object) array("test" => array("testing" => array("moretesting"))); var_dump($object);'

And


php -r '$obj->foo->bar->fooz = "Testing"; $array = (array) $obj; var_dump($array);'

Then you can see that casting is not working!? Just tried it on PHP 7.0.6.

reply Reply
Milch

A simpler way to do this would be:

$myArray = json_decode( json_encode($myObject), true);

The second argument for json_decode tells json_decode to use arrays. This has the added benefit of allowing for arrays in the objects.

reply Reply