从具有额外参数的扩展RecursiveIterator循环RecursiveIteratorIterator

时间:2012-02-08 16:47:32

标签: php iterator spl

假设我已关注ArrayObject

$array_object = new ArrayObject(array(
   array('1', '2', '3', '4'),
   array('3', '6', '7', '8'),
   array('9', '3', '11', '12'),
));

我扩展RecursiveFilterIterator只接受子元素,其值等于参数中传递的某个值:

class myRecursiveFilterIterator extends RecursiveFilterIterator
{
   public $value;

   public function __construct($it, $value)
   {
      parent::__construct($it);
      $this->value = $value;
   }

   public function accept()
   {
      return (parent::hasChildren()) || (parent::current() == $this->value);
   }
}

我创建了这个全新迭代器的实例,以过滤等于3的值:

$recursive_filter_iterator = new myRecursiveFilterIterator(new RecursiveArrayIterator($array_object), 3);

如果现在我使用myRecursiveFilterIterator

循环整个RecursiveIteratorIterator
foreach (new RecursiveIteratorIterator($recursive_filter_iterator) as $value) {
   var_dump($value);
}

我收到以下警告:

Warning: Missing argument 2 for myRecursiveFilterIterator::__construct() in /my/path/test.php on line myLine Notice: Undefined variable: value in /my/path/test.php on line myOtherLine

所以它就像循环RecursiveIteratorIterator尝试实例myRecursiveFilterIterator而没有传递第二个参数$value

如果我在不提供额外参数的情况下扩展FilterIterator,则不会发生这种情况。

1 个答案:

答案 0 :(得分:2)

我决定自己运行脚本,这就是注意到的内容

  1. 您正在使用多数组,因此parent::current()可以是一个数组,这意味着 下面的行是错误的,因为$this->value是一个整数。

    return (parent::hasChildren()) || (parent::current() == $this->value);
    
  2. $this->current ()也会将字符串切换到数组,您可以根据想要实现的目标来管理它们

    if (is_array ( $current )) {
        return ($this->hasChildren ()) || (in_array ( ( string ) $this->value, $this->current () ));
    } else {
    
        //var_dump ( $this->value, $this->current () );
    
        return ($this->hasChildren ()) || ( $this->value == $this->current ());
    }
    
  3. 您还需要实现getChildren方法,这就是为什么PHP抱怨myRecursiveFilterIterator::__construct()

    缺少参数2的原因
    public function getChildren() {
        return new self ( $this->getInnerIterator ()->getChildren (), $this->value );
    }
    
  4. ==============================丢弃老人的回应============== ===============

    PHP大多数都传达了错误的错误消息..您的代码很好,但是当您尝试直接使用foreach与RecursiveIteratorIterator时出现错误

    使用RecursiveArrayIterator封装RecursiveIteratorIterator是一种更好的方法:

    foreach (new RecursiveArrayIterator(new RecursiveIteratorIterator($recursive_filter_iterator)) as $value) {
        var_dump($value);
    } 
    

    :)