-1

I am wondering if there is a built-in way in PHP to cast multidimensional objects to arrays?

The problem is when applying a regular casting on an object, the first dimension only is being affected, all other dimensions remind the same.

Note: I am interested in casting only!

Example:

$a = new stdClass();
$a->b = 'qwe';
$a->c = new stdClass();
$a->c->d = 'asd';

var_dump((array)$a); // echoes:

array(2) {
  ["b"]=>
  string(3) "qwe"
  ["c"]=>
  object(stdClass)#2 (1) {
    ["d"]=>
    string(3) "asd"
  }
}

As you can see only the first dimension was affected, so how to cast multidimensional objects?

8
  • I didn't quite get it. Your code and output seems correct. What exactly you've expected it to do? Commented Aug 20, 2015 at 11:02
  • $a->c is still an object. I want it to be array. Commented Aug 20, 2015 at 11:03
  • 4
    Maybe duplicate? stackoverflow.com/questions/13567939/… Commented Aug 20, 2015 at 11:04
  • 2
    I don't think you can do that, at least with var_dump or print_r. You could build a foreach that echoes your style and forces array casting whenever it finds a property that's an object. Commented Aug 20, 2015 at 11:06
  • Guys, please read the question carefully. I asked whether there is a built-in way. No need to provide answers with recursion. It is not built-in. Commented Aug 20, 2015 at 11:07

2 Answers 2

6

There is no official way to cast a multi-level object to an array but the good news is that there is a hack.

Use json_encode() to get a JSON representation of your object then pass the result to json_decode() and use TRUE as its second argument to get arrays instead of objects.

$a = new stdClass();
$a->b = 'qwe';
$a->c = new stdClass();
$a->c->d = 'asd';

print_r(json_decode(json_encode($a), TRUE));

The output is:

Array
(
    [b] => qwe
    [c] => Array
        (
            [d] => asd
        )

)

The method has some drawbacks (it cannot handle resources, for example) but they are just minor annoyances.

Sign up to request clarification or add additional context in comments.

Comments

0

Since your question is if it's possible using only a single built-in PHP function to recursively cast object and children objects as array, without even any user-made callback function, the answer is no, it can't be done like that.

There are other ways to achieve it, though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.