I'm working on a double while loop in PHP to show results from a MySQL database in a grouped manner. This is an example of my database structure:
id name team country
1 Hamilton mercedes uk
2 Button mclaren uk
3 Alonso mclaren es
4 Perez mclaren mx
I want it displayed grouped like this:
ES
Alonso
MX
Perez
UK
Button
Hamilton
However my nested loop doesn't get any better than this:
ES
Alonso
MX
Alonso
Perez
UK
Alonso
Perez
Button
Hamilton
My loop is failing somewhere or I'm just taking the wrong approach. I tried increments, unnested loops, resetting vars, continue/break, but I can't figure it out. The first loop is to print a table structure per grouping. This is an example of my code:
<?php
// count unique country entries
$categories = $db->query("
SELECT DISTINCT country
FROM cms_drivers
WHERE team = '$team'
ORDER BY country
");
while ($cat = $db->fetch_array($categories)) { // loops 3 times
$custom = $db->query("
SELECT id, name, team, country
FROM cms_drivers
WHERE team = '$team' AND country = '$cat[country]'
ORDER BY name
");
while ($content = $db->fetch_array($custom)) {
process('$drivers_bits .= "' . fetch_template('cms_drivers_bits') . '";');
}
process('$drivers .= "' . fetch_template('cms_drivers') . '";');
}
Am I overlooking something really simple or is this just the wrong approach?
cms_drivers_bits template:
<tr><td>$content[name]</td></tr>
cms_drivers template:
<table cellpadding="8" cellspacing="0" width="100%">
<thead>
<tr>
<td class="header">
<span><strong>$cat[country]</strong></span></td>
</tr>
</thead>
<tbody>
$drivers_bits
</tbody>
</table>