PHP - Convert mixed array & objects recursively
Ever gotten back mixed data that contained arrays and objects? This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!
Example
<?php
abstract class Util {
public static function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__METHOD__, $d) : $d;
}
public static function array_to_object($d) {
return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
}
}
?>
Procedural way
<?php
function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}
function array_to_object($d) {
return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
?>
Written by Jason Oakley
Related protips
6 Responses
or you could just do...
$array = (array) $object;
$object = (object) $array;
Whoops. I should have probably included that this applies to mixed multidimensional arrays and objects. Type casting would only work at the top level and not apply to the children.
** I edited the tip to reflect that I originally intended.
Yes, you can type cast a single object or array. The point here is to do it recursively over a large array/object set.
Personally, I prefer to work with objects so this comes in handy to convert a multidimensional array into a series of parent/child objects. I have also run across instances of receiving large object sets where it makes more sense to work with arrays. That's where this comes in handy.
I really like the recursive logic using magic constants! Bonus points for not using a loop - array_map :)
Hi,
another subtle alternative : https://gist.github.com/victorbstan/744478
just what I needed top work