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. Both comments and trackbacks are currently closed.