How to convert a stdClass to array, recursively?

1

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';
$a->parentes->esposa = 'Cirlene';

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

So how can I convert this object to array recursively?

    
asked by anonymous 18.10.2015 / 00:40

1 answer

1

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

Create a function

Create a function 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;
}

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

json_decode(json_encode($object), true);
    
18.10.2015 / 00:47