你能解释一下,代码有什么问题吗?我试图摆脱所有不是1或2的元素......
$current_groups = [1,2,3,4];
for ($i = 0; $i < count($current_groups); $i++){
if ($current_groups[$i]!= 1 and $current_groups[$i] != 2){
unset($current_groups[$i]);
$i = $i - 1;
}
}
echo print_r($current_groups, true);
它意外地进入了无限循环......
答案 0 :(得分:6)
在for循环定义中,$i
在每次迭代后递增。
for ($i = 0; $i < count($current_groups); $i++){
然后在身体中$i = $i - 1;
,它会回到之前的值。所以,基本上它永远不会改变。
您可以使用array_filter
来代替。
$current_groups = array_filter($current_groups, function($x) {
return $x == 1 || $x == 2;
});
或array_intersect
(感谢@Chris的想法。)
$current_groups = array_intersect($current_groups, [1,2]);