I'm trying to write a recursive array iterator function in which the function will return a result set of all sets that are specified by '$needle'. Where $needle = key
Here is my function:
function recursive($needle, $array, $holder = array()) {
foreach ($array as $key => $value) {
if (gettype($value) == 'array') {
if ($key != $needle) {
recursive($needle, $value);
} elseif ($key == $needle) {
if (!empty($value)) {
array_push($holder, $value);
}
}
}
}
return $holder;
}
But I'm not getting all the results back and instead get a few empty results, if I don't specify the !empty($value)
, although the input array does not have any empty sets. What am I doing wrong?
More fine-grained control is perhaps possible with true (tm) recursive array traversal via
RecursiveIterator
interface and some key filters and array conversion functions:Providing an exemplary result as:
Full code example (Demo):
You don't need to reinvent the wheel since PHP has standard Recursive Iterator API:
-note, that, since you're searching for value by key - in common case
$value
will hold entire subsection.If you want to do this in your own recursive function, here's one:
A tiny modification of your construction:
$holder = recursive($needle, $value, $holder);
Ay?