基于MySQL结果,在PHP while循环内每第1次和第4​​次运行脚本

时间:2014-10-19 07:42:21

标签: php mysql loops while-loop

我从while表中获取了loop MySQL个数据。返回的行数未知。我想在每个第1和第4项上运行loop内的部分代码,例如:

while ($result = $stmt->fetch()) {

   //Run on first row always, then repeat on the 4th item and so on.
   echo '<div class="row">';

}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

// keep track of the iteration count
$i = 1;

while ($result = $stmt->fetch()) {

    //if it's the first iteration, open the row
    if($i == 1) { echo '<div class="row">'; }

    //...

    // NOTE: count($results) is pseudocode, make sure you provide it somehow
    // if you're on the 4nth or the last iteration 
    if($i % 4 == 0 or $i == count($results))
    {
        // close the row
        echo '</div>';

        // if it's not the last item in the loop, open a new row
        if($i != count($results)) { echo '<div class="row">'; }
    }

    $i++;
}