-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?

Boarking
  • 95
  • 1
  • 2
  • 6
  • I didn't quite get it. Your code and output seems correct. What exactly you've expected it to do? – al'ein Aug 20 '15 at 11:02
  • $a->c is still an object. I want it to be array. – Boarking Aug 20 '15 at 11:03
  • 4
    Maybe duplicate? http://stackoverflow.com/questions/13567939/convert-multidimensional-objects-to-array – sanderbee Aug 20 '15 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. – al'ein Aug 20 '15 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. – Boarking Aug 20 '15 at 11:07
  • It was answered as you requested => "*I don't think you can do that*". As complex your needs grow, better use of built-in functions you may make. There is no magic, as `array_walk_recursive` is a built-in, as exemple, but you have to pass it a callback function anyway. – al'ein Aug 20 '15 at 11:11
  • This is not possible using casting only. – Darragh Enright Aug 20 '15 at 11:23
  • There's a pretty simple workaround though. – Darragh Enright Aug 20 '15 at 11:27

2 Answers2

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.

axiac
  • 68,258
  • 9
  • 99
  • 134
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.

al'ein
  • 1,711
  • 1
  • 14
  • 21