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?
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;
}
}
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);
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) {
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With