Group mysql results in groups of four

半腔热情 提交于 2021-02-11 18:23:10

问题


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!!


回答1:


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.



来源:https://stackoverflow.com/questions/22697509/group-mysql-results-in-groups-of-four

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!