How to convert stdClass to array recursively?

Asked

Viewed 985 times

2

I have the following object:

$a = new stdClass;
$a->id = 1;
$a->nome = 'wallace';
$a->parentes = new stdClass;

$a->parentes->pai = 'Sidney';
$a->parentes->mae = 'Maria';

I know with a cast it is possible to convert the stdClass for array, but not recursively.

So how can I convert this object to array recursively?

2 answers

1

If the goal is to convert the object to array recursively, here are some tips.

Create a function

create a role for this:

function object_to_array(stdClass $object)
{
    $result = (array)$object;

    foreach($result as &$value) {

        if ($value instanceof stdClass) {
            $value = object_to_array($value);
        }
   }

    return $result;
}

To gambiarra json_encode solution combined with json_decode with True in the second parameter

json_decode(json_encode($object), true);
  • 1

    See also: http://stackoverflow.com/a/16023589

  • That one is tricky huh, @bfavaretto

-4

Depending on the PHP version you don’t need to create a function or anything like that, if your stdClass is just a scalar type (pure objects) you can simply use PHP’s own casting to do this (only version 7 up, 5.6 doesn’t work very well.

Example:

$object = new \StdClass;
$object->id = 12;
$object->name = "TEST"

var_dump((array)$object) // vai printar [ 'id' => 12, 'name' => 'test'];
  • 1

    but and the internal stdClass? the example was not very clear. If possible, post examples on ideone.com

  • scalar type includes internal objects, a stdClass no matter how many internal objects you have within it since they are scalar, they will become object array, for more reference I advise you to give a studied in PHP documentation in php.net.

  • 1

    About being scalar, I know. The question talks about recursive conversion, which is a stdClass inside the other.

  • 3

    Even the question itself starts from the premise that the cast works only on one level, so I don’t see this answer as answering the question, although it’s not wrong,

  • The answer was appropriate for the question, if you wanted it on more levels just do it correctly and anyway the cast (array) solves the objects within itself by creating an array of objects, in fact this is in the documentation itself and is not an argument, Just go in there and read.

  • 2

    Young man, I think you didn’t read the question right. The question talks about converting a stdClass for object RECURSIVELY

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.