1

( [0] => stdClass Object ( [name] => Ford [models] => Array ( [0] => Fiesta [1] => Focus [2] => Mustang )

    )

[1] => stdClass Object
    (
        [name] => BMW
        [models] => Array
            (
                [0] => 320
                [1] => X3
                [2] => X5
            )

    )

[2] => stdClass Object
    (
        [name] => Fiat
        [models] => Array
            (
                [0] => 500
                [1] => Panda
            )

    )

)

Vaibhav Shettar
  • 790
  • 2
  • 9
  • 20

2 Answers2

1

The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), True);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) {
    $array[] = $value->name;
}

Try it!

Sanjay Chaudhari
  • 420
  • 4
  • 13
1

Yes we can use JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however.

$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}
Amit Gupta
  • 2,771
  • 2
  • 17
  • 31