phparraysrecursioncasting

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?


Solution

  • 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) {