我试图遍历包含特定值的数组的前5个项目。
下面的代码导致无限循环。
$i = 0;
while ($i < 5):
if ($counselor[$i]->state == $state || !$state):
// do stuff
$i++;
endif;
endwhile;
基本上,我想在if语句运行5次后结束循环。
答案 0 :(得分:4)
尽管其他人已经解释了您的解决方案当前为何不起作用的原因以及解决方案,但是最好的选择是循环整个数组,直到找到5个匹配项为止-而是使用foreach
循环。
通过使用foreach
循环,如果数组的匹配元素少于5个(如果匹配元素少于5个,它将永不中断),您将永远不会遇到问题。
$i = 0;
// Loop the array
foreach ($counselor as $k=>$v) {
// Check if there is a match
if ($v->state == $state || !$state) {
// Do whatever if a match here
$i++;
}
// If we have found 5 matches, break out of the loop!
if ($i == 5) {
break;
}
}
您现在可以检查$i
的大小,如果小于5,则发现少于5个匹配项。如果正好是5,则找到了匹配项,并结束了循环。
答案 1 :(得分:2)
如果不满足if语句,那么您将只检查electron
。
当满足if语句时,您需要一个单独的计数器。
$counselor[0]->state
我还通过检查$ counselor [$ i]是否为null添加了边界检查。 (也可以检查$i = 0;
$containsCount = 0;
while ($containsCount < 5 || !isset($counselor[$i])):
if ($counselor[$i]->state == $state || !$state):
// do stuff
++$containsCount;
endif;
++$i;
endwhile;
)
答案 2 :(得分:1)
如果第一次if语句为false($ i = 0),则它将永远不匹配...因为$ i始终为0。对于$ i = 1、2、3或4也是一样。这些都是错误的,循环将被卡住。 $ i永远不会增加。您需要其他解决方案。
答案 3 :(得分:0)
仅当if语句返回true时,才递增$i
。如果您将$i++;
从if语句中删除,则循环将始终准确运行5次。
$i = 0;
while($i < 5):
if($counselor[$i]->state == $state || !$state):
// do stuff
endif;
$i++;
endwhile;
答案 4 :(得分:0)
您必须退出$i++
状态的if
:
$i = 0;
while($i < 5):
if($counselor[$i]->state == $state || !$state):
// do stuff
endif;
$i++;
endwhile;
答案 5 :(得分:0)
如果if()条件没有满足5次,它将是无限的,因为while()条件将永远不会满足。 代替while语句,使用匹配数组长度的循环,它将在到达数组末尾时结束。
答案 6 :(得分:0)
也许您可以尝试如下更改if语句:
UIView.animate(withDuration: 0.1, animations: {
self.destinationReachedAnnotation.coordinate = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude)
self.navigationView.setCenter(self.destinationReachedAnnotation.coordinate, zoomLevel: 17, animated: true)
self.navigationView.camera.centerCoordinate = currentLocation.coordinate
self.view.layoutIfNeeded()
}) { (completion) in
}