while 循环中的记录分组 | PHP

发布于 2024-08-27 07:20:50 字数 757 浏览 6 评论 0原文

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

--- 优先级:高 ---

记录...

--- 优先级:中 ---

记录...

--- 优先级:低 ---

记录...

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

标签:“优先级:[优先级]”必须设置在有关其级别的分组记录之上

编辑:

<?php

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

?>

就像那段代码——

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

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

--- Priority: High ---

Records...

--- Priority: Medium ---

Records...

--- Priority: Low ---

Records...

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'

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

EDIT:

<?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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转角预定愛 2024-09-03 07:20:50

如果您确定结果是按优先级排序的,那么就像这样微不足道的事情:

$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条件下测试优先级是否发生变化。如果是,则回显优先级并将当前优先级设置为当前行中找到的优先级。

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

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'];
}

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.

青春有你 2024-09-03 07:20:50

如果您使用 mysql 为什么不使用数据库排序功能?

SELECT *
FROM items
ORDER BY priority DESC

If you use mysql why would not you use DB ordering capabilities?

SELECT *
FROM items
ORDER BY priority DESC
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文