简体   繁体   English

如何获取不从FilterIterator传递的值

[英]How to get values that doesn't pass from FilterIterator

I'm using FilterIterator to filter out the values and implemented the accept() method successfully. 我正在使用FilterIterator筛选出值并成功实现了accept()方法。 However I was wondering how would it be possible to get the values that returned false from my accept method in single iteration. 但是我想知道如何在单次迭代中从我的accept方法获取返回false的值。 Let's take the code below as an example (taken from php.net ); 让我们以下面的代码为例(取自php.net );

class UserFilter extends FilterIterator 
{
    private $userFilter;

    public function __construct(Iterator $iterator , $filter )
    {
        parent::__construct($iterator);
        $this->userFilter = $filter;
    }

    public function accept()
    {
        $user = $this->getInnerIterator()->current();
        if( strcasecmp($user['name'],$this->userFilter) == 0) {
            return false;
        }        
        return true;
    }
}

On the code above, it directly filters out the values and returns the values that pass from the filteriterator. 在上面的代码中,它直接过滤掉值并返回从filteriterator传递的值。 Implemented as; 实施为;

$array = array(
array('name' => 'Jonathan','id' => '5'),
array('name' => 'Abdul' ,'id' => '22')
);

$object = new ArrayObject($array);
$iterator = new UserFilter($object->getIterator(),'abdul');

It will contain only the array with name Jonathan . 它仅包含名称为Jonathan的数组。 However I was wondering would it be possible to store the object with name Abdul in another variable using the same filter with a slight addition instead of reimplementing the entire filter to do the opposite ?. 但是我想知道是否有可能使用相同的过滤器并稍加添加将名称为Abdul的对象存储在另一个变量中,而不是重新实现整个过滤器以执行相反的操作 One way I was thinking would exactly copy paste the FilterIterator and basically change values of true and false . 我想到的一种方法是完全复制粘贴FilterIterator并基本上更改truefalse的值。 However are there any neat ways of doing it, since it will require another traversal on the list. 但是,有任何整齐的方法可以执行此操作,因为这将需要列表上的另一个遍历。

I think you must rewrite the accept() mechanic. 我认为您必须重写accept()机制。 Instead of returning true or false, you may want to break down the array to 您可能需要将数组分解为以下内容,而不是返回true或false:

$result = array(
    'passed' => array(...),
    'not_passed' => array(...)
);

Your code may look like this 您的代码可能如下所示

if (strcasecmp($user['name'], $this->userFilter) == 0) {
    $result['not_passed'][] = $user;
} else {
    $result['passed'][] = $user;
}

return $result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM