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
            )

    )

)

2
  • What do you want to do with it? What you want has a huge impact as to how to parse it. Are you asking about how to loop through every item? Commented Nov 15, 2017 at 6:52
  • Mean casting to array (array) ? Commented Nov 15, 2017 at 6:52

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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!

1 Comment

Have you tried?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.