我总是在ArrayIterator的前面丢失第二项(#1),并删除每个元素。
$cnt = 0;
$a = new ArrayIterator();
$a->append(++$cnt);
$a->append(++$cnt);
$a->append(++$cnt);
$a->append(++$cnt);
$a->append(++$cnt);
foreach ($a as $i => $item) {
print_r("$i => $item".PHP_EOL);
$a->offsetUnset($i);
}
print_r('count: '.$a->count().PHP_EOL);
foreach ($a as $i => $item) {
print_r("lost! $i => $item".PHP_EOL);
}输出:
0 => 1
2 => 3
3 => 4
4 => 5
count: 1
lost! 1 => 2这怎么可能呢?oO
$ php -v
PHP 5.5.37 (cli) (built: Jun 22 2016 16:14:46)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies发布于 2016-07-22 21:16:07
祝贺你!您已找到一个documented bug in ArrayIterator
摘录:
在循环遍历时对数组中的第二个元素调用offsetUnset();时,
ArrayIterator始终跳过该元素。
在实际的ArrayObject中使用来自迭代器的键并取消设置,效果与预期一样。
发布于 2016-07-22 21:12:53
看起来,只有使用offsetUnset方法才能耗尽ArrayIterator。那就是使用do..while
do {
print_r("{$a->key()} => {$a->current()}".PHP_EOL);
$a->offsetUnset($a->key());
} while ($a->count());
print_r('count: '.$a->count() . PHP_EOL);输出:
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
count: 0https://stackoverflow.com/questions/38527123
复制相似问题