Convert multiple object to array in PHP

For simple object, just use cast syntax should be fine.

$array = (array)$object;

However, this way doesn’t work for complexed object (or array+object combination) like this:

array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(1)
  }
}

Then, simply this one liner works well.

$multipleArray = array_map('get_object_vars', $complexedObject);

Since I’m getting use more json_decode(), I get “PHP Fatal error: Cannot use object of type stdClass as array” sometimes. Actually in this context, to use the second parameter of json_decode is the simplest way.

$it_will_be_array = json_decode($json, true);
This entry was posted in Tweak and tagged . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

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=""> <strike> <strong> <pre lang="" line="" escaped="">

  • About

    I'm Nobu, a web developer living in Mountain View, CA. Feel free to comment on any posts. I'm also tweeting on twitter.

  • Archives

  • Recent Posts