views:

178

answers:

3

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.

A: 

It depends on how many records you have. If it's a lot, use a database table and have a priority_level column. Otherwise you can just use a multiple-dimensional array $a['high']['field'], $['low']['field'], etc or: $a = array(1=>array('low1', 'low2'), 2=>array('med1', 'med2'), 3=>array('high2', 'high2'));

rkulla
Edited the post
YouBook
A: 

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

SELECT *
FROM items
ORDER BY priority DESC
newtover
Not the query... I've already got it ordered by it, i'm asking about the PHP that seperates records. - edited the post btw
YouBook
+1  A: 

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.

fireeyedboy
Accepted solution, thanks :)
YouBook
Ah.. it's kind of not working, but it does 'group' the records but it just gives a label each record not label per group.
YouBook
Are you sure the resultset is ordered by priority? Can you edit your question and show the SQL query in there?
fireeyedboy
Oops, my bad, did it incorrectly, but your solution still works :) no problem at all
YouBook
Alright Wayne. Good to hear.
fireeyedboy