I have a multidimensional array in PHP and want to be able to search through it and find all values that are objects.
The reason I want to do this is so that when an object is found I can replace it with an array by calling an output() method on it. The output() method uses get_object_vars() to turn itself into an array, which it then returns.
Here’s an example which achieves what I want manually (but only with 2 levels of depth):
// First level search...
foreach($array as $k => $v) {
// Check if it's an array.
if (is_array($v)) {
// Second level search...
foreach($v as $k2 => $v2) {
// If it's an object - convert it!
if (is_object($v2)) {
$array[$k][$k2] = $array[$k][$k2]->output();
}
}
}
// If it's an object - convert it!
if (is_object($v)) {
$array[$k] = $array[$k]->output();
}
}
Tim Cooper’s answer is wrong because the function must have a parameter that is passed by reference and not by value.
Versus passing by reference: