8

我正在尝试编写一个递归数组迭代器函数,其中该函数将返回由“$needle”指定的所有集合的结果集。$needle = 钥匙

这是我的功能:

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)尽管输入数组没有任何空集。我究竟做错了什么?

4

3 回答 3

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;
}
于 2013-10-31T14:47:40.860 回答
1

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

$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);
于 2013-10-31T15:15:36.557 回答
0

对您的结构进行微小修改:

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

啊?

于 2013-10-31T14:58:26.180 回答