We recently needed to convert a complex array structure to an object-based one in PHP. We started off with Marcel’s array2object function but realized that we only wanted to “objectify” associative arrays, and leave non-associative arrays to as arrays. So here’s the final function, using vhermecz’s function to detect associative arrays:
function array2object($data) {
if (!is_array($data)) return $data;
$is_assoc = is_assoc($data);
$object = new stdClass();
if (count($data) == 0) return $data;
if (is_array($data) && count($data) > 0) {
foreach ($data as $name=>$value) {
if ($name !== '') {
$object->$name = array2object($value);
$data[$name] = array2object($value);
}
}
}
if ($is_assoc)
return $object;
else
return $data;
}
function is_assoc($var) {
return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}
