简体   繁体   中英

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

I have a while loop fetching data from a MySQL table. The number of returned rows is unknown. I want to run parts of code inside the loop on every 1st and 4th item, like:

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

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

}

How can I do this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM