簡體   English   中英

根據MySQL結果在PHP while循環中每1和4一次運行腳本

[英]Run script every 1st and 4th time inside a PHP while loop based on MySQL result

我有一個while loopMySQL表中獲取數據。 返回的行數未知。 我想在每個第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">';

}

我怎樣才能做到這一點?

// 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++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM