...

View Full Version : Grouping results under category headings



mat
01-08-2004, 07:17 AM
I am wanting to to group my results by category (under that category heading)

Code with simplified html:


<? while ($vacancies = mysql_fetch_assoc($vacancies_result)) { ?>

<? if ($current_category != $vacancies['category']) { $current_category = $vacancies['category'] ?>
<strong><? echo $current_category ?></strong>
<? } ?>

<br>
<? echo $vacancies['title'] ?>

<? } ?>



What I am looking for is something like this:

Transport
bus driver
taxi driver


But i'm getting:

Transport
bus driver

Transport
taxi driver




:(

raf
01-08-2004, 09:58 AM
You need to check if
$vacancies['category']

is differnt from the $vacancies['category']) of the previous record (which you store in a variable that after the comparison is set to $vacancies['category']), and only print the break and category when it's different.

More info and examplecode:
http://www.codingforums.com/showthread.php?s=&threadid=29119&highlight=previous
http://www.codingforums.com/showthread.php?s=&threadid=30741&highlight=previous
http://www.codingforums.com/showthread.php?s=&threadid=29700&highlight=previous

mat
01-09-2004, 09:52 AM
OK, thanks. checked the examples and I think i understand better now, yet I must still missing something as I still get the same result with the following code:



<? $previous_cat = "x"; ?>
<? while ($vacancies = mysql_fetch_assoc($vacancies_result)) { ?>

<? if ($previous_cat != $vacancies['category']){ ?>
<br><strong><? echo $vacancies['category'] ?></strong>
<? } ?>

<br>
<? echo $vacancies['title'] ?>

<? $previous_cat = $vacancies['category']; ?>
<? echo $previous_cat ?>
<? } ?>

raf
01-09-2004, 10:23 AM
<?php
$previous_cat = "x";
while ($vacancies = mysql_fetch_assoc($vacancies_result)) {
if ($previous_cat != $vacancies['category']){
echo ('<br /><strong>' . $vacancies['category'] .'</strong>');
}
echo ('<br />' . $vacancies['title'] );
$previous_cat = $vacancies['category'];
}
?>

should work just fine.

Oh yeah, in case you didn't realise --> you need to have an 'ORDER BY category ' clause in your selectstatement.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum