Forum Moderators: coopster

Message Too Old, No Replies

Outputting data in categories

Printing the category once

         

johnglass

6:35 am on Apr 6, 2004 (gmt 0)

10+ Year Member



Hi,

I'm trying to organize some data into categories. Lets say for example we have this:

while ($row = mysql_fetch_assoc($result))
{
$data1 = $row["field1"];
$data2 = $row["field2"];
$data3 = $row["field3"];
$data4 = $row["category"];
echo $data4?><br><?php;
echo $data1,$data2,$data3?><br><?php;
}

Which would have a sample output like this:

Category1
Field1Field2Field3
Category1
Field1Field2Field3
Category2
Field1Field2Field3
Category2
Field1Field2Field3

How would I get it to print the category name once, then everything belonging to that category, then move to the next category, etc. So it'd look like this:

Category1
Field1Field2Field3
Field1Field2Field3
Category2
Field1Field2Field3
Field1Field2Field3

That's the simplest way I can think of putting it. :)

Seems to me like it'd be an easy answer, but I've tried a couple of different approaches and can't seem to get it to work.

Thanx :)

johnglass

barn_de

7:47 am on Apr 6, 2004 (gmt 0)

10+ Year Member



Hi johnglass,

this is from a other thread i posted yesterday. i just modified it for your needs:

while ($row = mysql_fetch_assoc($result))
{
$data1 = $row["field1"];
$data2 = $row["field2"];
$data3 = $row["field3"];
$sCat = $row[category'];

if ($sCat!= $sCatOld) {
echo $sCat . "<br>\n";
}
echo $data1,$data2,$data3; . "<br>\n";
$sCatOld = $sCat;
}

should work.

barn

johnglass

8:09 am on Apr 6, 2004 (gmt 0)

10+ Year Member



Aaaaahhh... I see how that works. Very cool :)

And it worked perfectly for me, thanx!

johnglass

dcrombie

9:39 am on Apr 6, 2004 (gmt 0)



You can make a small change and save a few ms:

while ($row = mysql_fetch_assoc($result)) { 
$data1 = $row["field1"];
$data2 = $row["field2"];
$data3 = $row["field3"];
$sCat = $row["category"];

if ($sCat!= $sCatOld) {
echo "$sCat<br>\n";
$sCatOld = $sCat;
}
echo "$data1,$data2,$data3<br>\n";
}