简体   繁体   English

将mysql组分为四个组

[英]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: 我想将sql select的结果分组为四行,以动态进行如下所示:

<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). 例如,如果我在数据库中有19行,我想创建4个div(最后一个有3行)。 This is for a bootstrap gallery, and the div will have the class .row with 4 columns (the four results from the database). 这是用于引导画廊的,并且div将具有带有四列的.row类(数据库中的四个结果)。 I have 8 images, two divs with the class .row need to be created. 我有8张图片,需要创建带有.row类的两个div。

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: 您可以使用模运算符将行分为4组,如下所示:

$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. 这样会将结果分成4组,如下所示: <div>row 1 row 2 row 3 row 4</div><div>row 5 row 6 row 7 row 8</div>等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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