Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 0
[6] => 1
[7] => 0
[8] => 0
)
应该这样做: (完全删除以前的元素)
found [5] => 0 then unset [4] => 1 and unset [5] => 0
found [7] => 0 then unset [6] => 1 and unset [7] => 0
found [8] => 0 then unset [3] => 1 (because 7,6,5,4 were already deleted)
and unset[8] => 0
结果:
Array
(
[1] => 1
[2] => 1
)
我尝试过这样的事情,但它只会扰乱当前元素,为什么?
foreach ($points as $key => $value) {
if ($value == '0') {
unset($points[$key]);
$prev = prev($points);
unset($prev);
}
}
答案 0 :(得分:4)
当您使用foreach
迭代数组时,您无法使用prev
进行导航 - 因为数组只有一个指针而foreach
和prev
将对其进行战斗
您需要选择兼容的方式。
例如,只有数组函数:
for(
reset($points);
$value = current($points), $key = key($points), $key !== null;
next($points)
) {
if ($value == '0') {
unset($points[$key]);
prev($points);
$key = key($points);
if ($key === null) {
end($points);
$key = key($points);
}
unset($points[$key]);
prev($points);
}
}
结果:
Array
(
[1] => 1
[2] => 1
)
有一些警告:
unset($prev)
仅取消设置变量,您要取消设置数组条目prev()
不再有效。这就是end()
用于跳转到最后一个元素的原因。这是使用foreach的另一种方法。使用以前使用正确值迭代的键的附加堆栈被保留,以便可以移除先前的值(直到没有任何先前的值):
$lastKeys = [];
foreach ($points as $key => $value)
{
if ($value == '0') {
$lastKey = array_pop($lastKeys);
if ($lastKey !== null) {
unset($points[$lastKey]);
}
unset($points[$key]);
continue;
}
$lastKeys[] = $key;
}