PHP stdClass to Array and Array to stdClass – stdClass Object

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 multidimensional Objects to Arrays and multidimensional Arrays to Objects.

Function to Convert stdClass Objects to Multidimensional Arrays

Function to Convert Multidimensional Arrays to stdClass Objects

Function usage

Test output:

Share this post

50 Comments

  1. Thanks,

    Reply
  2. I’ve always just done this: $array = (array)$object;

    Reply
    • Hi Nigell,

      As I said at the beginning, this is easy if arrays and objects are one-dimensional. Your method doesn’t work with multidimensional arrays and objects.

      Try following:

      Output:

      First dimension is converted to array, but all others are still stdClass Objects, right?

      When you use objectToArray function output looks following:

      All stdClass Objects are converted to arrays.

      Reply
  3. Really appreciate this post! Helped me a lot! :)

    Reply
  4. Thank you so much for this post, you saved me countless hours!!!

    Reply
  5. Thanks…………. it’s save my time.

    Reply
  6. Thank you so must for posting this. You made my Sunday night coding not as bad as it could have been.

    Reply
  7. You don’t really need all this :-)
    Typecasting works!

    Try:

    Reply
    • Hi Tobi,

      Run following to see difference with typecasting and arrayToObject function:

      Typecasting won’t work (unfortunately) with multidimensional arrays.

      Reply
  8. THANKSSSS! great job!!!

    If someone needs this method inside a static class change the line… return array_map(__FUNCTION__, $d); for this one return array_map([__CLASS__, __METHOD__], $d);

    Reply
  9. Hello Tobi,
    Thank you thanky you!!
    You helped me so much

    Reply
  10. no need for and of that.

    $a = array(‘key’ => ‘value’, ‘another key’ => ‘another value’);

    var_dump(json_decode(json_encode($a)));

    Reply
  11. Very nice functions; really helpful to work with AngularJS when sending POST data to PHP, since the way you receive it is as a stdClass object.

    Thanks a lot!

    Reply

Submit a Comment

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

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