对来自 while 循环的记录进行分组 |PHP [英] Grouping records from while loop | PHP

查看:23
本文介绍了对来自 while 循环的记录进行分组 |PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按优先级对记录进行分组,例如

I'm trying to group down records by their priority levels, e.g.

--- 优先级:高---

记录...

--- 优先级:中---

记录...

--- 优先级:低---

记录...

类似的事情,我如何在 PHP 中做到这一点?while 循环按具有 int 值(高 = 3,中 = 2,低 = 1)的优先级列对记录进行排序.例如WHERE 优先级 = '1'

Something like that, how do I do that in PHP? The while loop orders records by the priority column which has int value (high = 3, medium = 2, low = 1). e.g. WHERE priority = '1'

标签:Priority: [priority level]" 必须设置在关于其级别的分组记录之上

The label: "Priority: [priority level]" has to be set above the grouped records regarding their level

<?php

while($row = mysql_fetch_array($result))
{
    echo '<h1>Priority Level: ' . $row['priority'] . '</h1>';
    echo $row['name'];
}

?>

就像那段代码一样 -

标签是一个标签,用于将记录的优先级分开.

Like that piece of code - the

tags is the label which seperates records regarding their priority level.

推荐答案

如果你确定结果是按优先级排序的,那么像下面这样的小事:

If you're sure the results are ordered by priority then something as trivial as this:

$priority = null;
while($row = mysql_fetch_array($result))
{
    if( $row['priority'] != $priority )
    {
        echo '<h1>Priority Level: ' . $row['priority'] . '</h1>';
        $priority = $row['priority'];
    }
    echo $row['name'];
}

换句话说,您在 $priority 变量中跟踪当前的优先级.然后在if条件中测试优先级是否发生了变化.如果是,则echo优先级并将当前优先级设置为当前行中找到的优先级.

In other words, you keep track of the current priority level in the $priority variable. Then test whether the priority has changed in the if condition. If so, echo the priority and set the current priority to the priority found in the current row.

请注意,如果行按优先级排序,这只会按预期工作(真正分组一次).换句话说,当不同的优先级没有分散在结果集中时.

Mind you, this only works as expected (truly grouped once) if the rows are ordered by priority. In other words, when different priorities are not scattered across the resultset.

这篇关于对来自 while 循环的记录进行分组 |PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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