简体   繁体   中英

Group mysql results in groups of four

I want to group the result of a sql select in groups of four rows to make dynamically something like this:

<div>
4 rows of the database
</div>

For example, if I have 19 rows in the database, I want to create 4 divs (the last one with the 3 remaining rows). This is for a bootstrap gallery, and the div will have the class .row with 4 columns (the four results from the database). I have 8 images, two divs with the class .row need to be created.

I think this will be achieved with loops, but I can´t find the way.

NOTE: i have coded in a very simplistic way, only to try to explain what I'm looking for. Thanks to all in advance!!

You can make use of the modulus-operator to group your rows into groups of 4, like this:

$i=0;
while($row = ...) {
    if($i%4 == 0) { // % = modulus operator. This returns the remainder of a division, so 1%4 = 1 (because it's 0+1/4), while 5%4 also returns 2 (5%4 = 1+1/4)
       if($i > 0) {
          echo '</div>';
       }
       echo '<div>';
   }
   echo $row;
   $i++;
}
echo '</div>';

This will group your results in sets of 4 like so: <div>row 1 row 2 row 3 row 4</div><div>row 5 row 6 row 7 row 8</div> etc.

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