PHP - 递归多维数组的迭代器 [英] PHP - Recursive Multidimension Array iterator
问题描述
我想写一个递归迭代器阵列功能,其中函数将返回设置由'$针规定的所有集合的结果。其中$ =针键
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
下面是我的功能:
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?
推荐答案
您不必推倒重来,因为PHP有标准的递归迭代 API:
You don't need to reinvent the wheel since PHP has standard Recursive Iterator API:
//$array is your multi-dimensional array
$result = [];
$search = 'foo';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value)
{
if($search==$key && $value!=='')
{
$result[] = $value;
}
}
- 注意,是因为你正在寻找价值的按键的 - 在通常情况下 $值
将持有整个小节
-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:
function recursive($needle, $array, $holder = [])
{
$holder = [];
foreach($array as $key=>$value)
{
if($key===$needle && $value!=='')
{
$holder = array_merge($holder, [$value]);
}
if(is_array($value))
{
$holder = array_merge($holder, recursive($needle, $value, $holder));
}
}
return $holder;
}
这篇关于PHP - 递归多维数组的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!