0

( [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 S
  • 710
  • 1
  • 9
  • 19

2 Answers2

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,623
  • 2
  • 16
  • 29
0

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
  • 410
  • 3
  • 13