正如标题所说:我有一个foreach循环,但循环每三次传递它必须做其他事情。这该怎么做?提前致谢。我试过了:
$count = 0
foreach ($cObjects as $oObject) {
if ($count <= 2) {
//do things
$count = 0;
} else {
// do other things
}
$count++;
}
这不起作用,同时每次将计数重置为0。
将if($count <= 2)
替换为if($count == 2)
。
答案 0 :(得分:2)
Parixit的答案仅适用于索引数组,对于集合或关联数组,您需要一个单独的$ count变量,如下所示:
$count = 0
foreach ($cObjects as $oObject) {
if ($count == 2) {
//do things
$count = 0;
} else {
// do other things
}
$count++;
}
答案 1 :(得分:1)
我不知道我理解它与否。但你应该做这样的事情
foreach($all as $k=>$single) {
if($k%3==0) {
//do every third time
continue;
}
//do something which will not execute every third time
}