分组 mysql 结果为四人一组 [英] Group mysql results in groups of four

查看:43
本文介绍了分组 mysql 结果为四人一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 sql select 的结果分组为四行一组,以动态生成如下内容:

4行数据库

例如,如果我在数据库中有 19 行,我想创建 4 个 div(最后一个包含 3 个剩余行).这是用于引导程序库的,div 将具有 .row 类和 4 列(来自数据库的四个结果).我有 8 张图片,需要创建两个 .row 类的 div.

我认为这可以通过循环来实现,但我找不到方法.

注意:我以非常简单的方式编码,只是为了解释我在寻找什么.提前谢谢大家!!

解决方案

您可以使用 modulus-operator 将您的行分组为 4 组,如下所示:

$i=0;while($row = ...) {if($i%4 == 0) {//% = 模运算符.这将返回除法的余数,因此 1%4 = 1(因为它是 0+1/4),而 5%4 也返回 2(5%4 = 1+1/4)如果($i > 0){回声'</div>';}echo '

';}回声 $row;$i++;}回声'</div>';

这会将您的结果分为 4 组,如下所示:<div>row 1 row 2 row 3 row 4</div><div>row 5 row 6 row 7 row 8</div> etc.

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.

这篇关于分组 mysql 结果为四人一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆