对来自 while 循环的记录进行分组 |PHP

2021-12-26 00:00:00 while-loop grouping php mysql

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

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.

相关文章