英文:
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
*/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论