I am fetching an array of animal names, types, age, etc. from a MySQL DB. I want to divide these into sections for ages like so…
Ages 5 - 10
Dog named Brian
Cat named Kitty
Dog named Buster
Ages 10+
Cat named Moody
Dog named Milo
Here’s how I am doing it right now (the query is already order by age):
while ($results = mysql_fetch_array($animals) {
if (($results[age] <= 10 && $results[age] >= 5) && !$head1 && !$head1display) {
$head1 = 'Ages 5 to 10<br />';
$head1display++;
} else $head1 = NULL;
if ($results[age] > 10 && !$head2 & !$head2display) {
$head2 = 'Ages 10+<br />';
$head2display++;
} else $head2 = NULL;
echo $head1.$head2.$results[type].' named '.$results[name].'<br />';
}
Is there a better way to do this? Keep in mind I don’t want to have two queries or two loops…
I would suggest using doing grouping/ordering in your SQL to fetch the animals already in the right way, such as:
Then in you php you can do almost direct output: