PHP – 从迭代器中取消设置一个值

huangapple go评论68阅读模式
英文:

PHP - unset a value from Iterator

问题

You can use the following code to unset a value in a filter iterator:

你可以使用以下代码来取消过滤迭代器中的某个值:

$iterator->rewind();
while ($iterator->valid()) {
    if ($iterator->current() === $valueToRemove) {
        $iterator->offsetUnset($iterator->key());
    }
    $iterator->next();
}

请将 $iterator 替换为你实际使用的迭代器变量,将 $valueToRemove 替换为要移除的值。

英文:

I have a filter iterator. How can a unset a give value in it. I have tried unset($list[$key]), but that gives me an error : Cannot use object of type Filter as array

答案1

得分: 2

The documentation states that the FilterIterator "filters out unwanted values," and the logic behind that is in the accept() method which you must implement.

So you don't unset anything, you just reject (or not accept, technically) values you don't want.

class DoctorFilter extends FilterIterator
{
    public function accept(): bool
    {
        $obj = $this->getInnerIterator()->current();
        
        return is_string($obj) && str_starts_with($obj, 'Dr.');
    }
}

$people = [
    'Dr. Jekyll',
    'Mr. Hyde', // This item will be removed
    'Dr. Frankenstein',
];

foreach (new DoctorFilter(new ArrayIterator($people)) as $item) {
    echo $item.PHP_EOL;
}

/*
Outputs:

Dr. Jekyll
Dr. Frankenstein
*/

Demo: https://3v4l.org/ieTAP#v8.2.6

英文:

The documentation states that the FilterIterator "filters out unwanted values", and the logic behind that is in the accept() method which you must implement.

So you don't unset anything, you just reject (or not accept, technically) values you don't want.

class DoctorFilter extends FilterIterator
{
    public function accept(): bool
    {
        $obj = $this->getInnerIterator()->current();
        
        return is_string($obj) && str_starts_with($obj, 'Dr.');
    }
}

$people = [
    'Dr. Jekyll',
    'Mr. Hyde', // This item will be removed
    'Dr. Frankenstein',
];

foreach (new DoctorFilter(new ArrayIterator($people)) as $item) {
    echo $item.PHP_EOL;
}

/*
Outputs:

Dr. Jekyll
Dr. Frankenstein
*/

Demo: https://3v4l.org/ieTAP#v8.2.6

huangapple
  • 本文由 发表于 2023年5月18日 00:16:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定