Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Recursively Convert Object to Array

I am trying to recursively convert a php object to an array. The function I wrote is this:

public function object_to_array($obj) {
    $array = (array) $obj;
    foreach ($array as $attribute) {
      if (is_array($attribute)) $attribute = $this->object_to_array($attribute);
      if (!is_string($attribute)) $attribute = (array) $attribute;
    }
    return $array;
}

However, I still end up with objects in my outer array. Why is this? Is my function incorrect?

like image 647
735Tesla Avatar asked Mar 27 '14 00:03

735Tesla


4 Answers

Here's my version. First it will test if the parameter passed is an array or object. If so it'll convert to array (if necessary) then run through each element (by reference) and recursively run the function on it. When it gets to a scalar value it will just return the value unmodified. Seems to work :-)

function object_to_array($obj) {
    //only process if it's an object or array being passed to the function
    if(is_object($obj) || is_array($obj)) {
        $ret = (array) $obj;
        foreach($ret as &$item) {
            //recursively process EACH element regardless of type
            $item = object_to_array($item);
        }
        return $ret;
    }
    //otherwise (i.e. for scalar values) return without modification
    else {
        return $obj;
    }
}
like image 189
james-geldart Avatar answered Nov 19 '22 11:11

james-geldart


You need to operate recursively.

This is the shortest I could come up with:

$toArray = function($x) use(&$toArray)
{
    return is_scalar($x)
        ? $x
        : array_map($toArray, (array) $x);
};

$array = $toArray($object);
like image 37
Sean Morris Avatar answered Nov 19 '22 10:11

Sean Morris


You want to check if it's an object not an array, though you might do both:

if (is_object($attribute) || is_array($attribute)) $attribute = $this->object_to_array($attribute);
//I don't see a need for this
//if (!is_string($attribute)) $attribute = (array) $attribute;

And from Aziz Saleh, reference $attribute so you can modify it:

foreach ($array as &$attribute) {
like image 3
AbraCadaver Avatar answered Nov 19 '22 09:11

AbraCadaver


Try using PHPs built in ArrayObject. It allows you to treat an object as an array.

http://www.php.net/manual/en/class.arrayobject.php

like image 3
Lee Salminen Avatar answered Nov 19 '22 09:11

Lee Salminen