Grouping records from while loop | PHP

前端 未结 2 1194
旧时难觅i
旧时难觅i 2021-01-21 07:20

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

--- Priority: High ---

Records...

相关标签:
2条回答
  • 2021-01-21 07:27

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

    SELECT *
    FROM items
    ORDER BY priority DESC
    
    0 讨论(0)
  • 2021-01-21 07:38

    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.

    0 讨论(0)
提交回复
热议问题