当我实现一个实现 Iterator 和 ArrayAccess 用于测试目的的类时,我没有遇到您的问题:
<?php
class a implements Iterator, ArrayAccess {
public $items = array();
private $index = 0;
public function current() {
return $this->items[$this->index];
}
public function key() {
return $this->index;
}
public function next() {
++$this->index;
}
public function rewind() {
$this->index = 0;
}
public function valid() {
return array_key_exists($this->index, $this->items);
}
public function offsetExists($offset) {
return array_key_exists($offset, $this->items);
}
public function offsetGet($offset) {
return $this->items[$offset];
}
public function offsetSet($offset, $value) {
$this->items[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->items[$offset]);
}
public function remove($item) {
foreach($this->items as $index => $itemsItem) {
if( $itemsItem == $item) {
unset($this->items[$index]);
break;
}
}
}
}
$a = new a();
array_map(array($a, 'offsetSet'), range(0, 100), range(0, 100));
foreach($a as $item) {
if( $item % 2 === 0 ) {
$a->remove($item);
}
}
var_dump($a->items);
如果您实现了迭代器,请对其进行更改,以确保在调用“下一个”和“当前”时删除一个项目不会使“a”实例返回不同的项目。
否则,你可以试试这个:
$mustBeRemoved = array();
foreach($a as $item) {
if(mustBeRemoved()) {
$mustBeRemoved []= $item;
}
}
foreach($mustBeRemoved as $item) {
$a->remove($item);
}
unset($mustBeRemoved);