PHP - 递归多维数组迭代器

时间:2013-10-31 14:37:21

标签: php arrays recursion

我正在尝试编写一个递归数组迭代器函数,其中函数将返回由'$ needle'指定的所有集合的结果集。其中$ 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;
}

但是我没有得到所有结果而是得到一些空结果,如果我没有指定!empty($value),尽管输入数组没有任何空集。我做错了什么?

3 个答案:

答案 0 :(得分:17)

由于PHP具有标准的Recursive Iterator API:

,因此您无需重新发明轮子
//$array is your multi-dimensional array
$result   = [];
$search   = 'foo';
$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(
        $array,
        RecursiveArrayIterator::CHILD_ARRAYS_ONLY
    )
); 

foreach($iterator as $key=>$value)
{
   if($search==$key && $value!=='')
   {
      $result[] = $value;
   }
}

- 注意,因为您正在按键搜索值 - 通常情况下$value将保留整个小节。

如果您想在自己的递归函数中执行此操作,请参阅:

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;
}

答案 1 :(得分:1)

通过RecursiveIterator接口的 true (tm)递归数组遍历以及一些关键过滤器和数组转换函数,可能可以实现更细粒度的控制:

$needle = '0';
$array  = [[1]];

$it = new KeyFilter(
    new RecursiveIteratorIterator(
        new MyRecursiveArrayIterator($array)
        , RecursiveIteratorIterator::SELF_FIRST
    )
    , $needle
);

$result = iterator_to_array($it, FALSE);
var_dump($result);

提供示例性结果:

array(2) {
  [0] =>
  array(1) {
    [0] =>
    int(1)
  }
  [1] =>
  int(1)
}

完整代码示例(Demo):

<?php
/**
 * @link http://stackoverflow.com/q/19709410/367456
 */

Class MyRecursiveArrayIterator extends ArrayIterator implements RecursiveIterator
{
    public function hasChildren()
    {
        $current = $this->current();
        return is_array($current) && count($current);
    }

    public function getChildren()
    {
        return new self($this->current());
    }
}

class KeyFilter extends RegexIterator
{
    public function __construct(Iterator $iterator, $key)
    {
        parent::__construct(
            $iterator, '/' . preg_quote($key) . '/', NULL, RegexIterator::USE_KEY
        );
    }
}

$needle = '0';
$array  = [[1]];

$it = new KeyFilter(
    new RecursiveIteratorIterator(
        new MyRecursiveArrayIterator($array)
        , RecursiveIteratorIterator::SELF_FIRST
    )
    , $needle
);

$result = iterator_to_array($it, FALSE);
var_dump($result);

答案 2 :(得分:0)

对建筑的微小修改:

$holder = recursive($needle, $value, $holder);

Ay的?