問題描述
我正在嘗試按優先級對記錄進行分組,例如
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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!