PHP在foreach循环中每隔x次执行其他操作

时间:2014-07-23 04:24:02

标签: php loops foreach

正如标题所说:我有一个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)

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
}