Consider this data:
make model color
---- ----- -----
Volskwagen Golf Red
Volskwagen Golf Green
Volskwagen Golf Blue
Toyota Corolla Red
Toyota Corolla Green
Toyota Corolla Blue
Toyota Corolla Black
The below code will run through this data and effectively group the vehicle make and models:
$sql = "SELECT make, model, color FROM t_cars ORDER BY make, model;";
$rows = $db->query($sql);
$group = '';
foreach ($rows as $row) {
if ($group != $row['make'].$row['model']) {
echo $row['color'] . '<br />';
$group = $row['make'].$row['model'];
}
}
The output will be simply:
red
red
What I want to be able to do is output (within the foreach
somewhere is:
'There are 3 Volkswagen Golfs. The colors are Red, Green, Blue'
'There are 4 Toyota Corollas. The colors are Red, Green, Blue, Black'
My actual code is much more complex than this, but if I get this logic right, I should be ok. The only constraint is that I need all this in the one containing foreach
statement like in the demo.
If you're using mysql and willing to change your sql query, you can use this query to help you out.
SELECT make, model, group_concat(color separator ',') AS colors, count(color) as colorcount FROM database GROUP BY make, model
Okay.
This will leave you with a query that would return:
[Volskwagen] [Golf] [Red,Green,Blue] [3]
[Toyota] [Corolla] [Red,Green,Blue,Black] [4]
Then you can do if colorcount > 1 add s to "Golf." You can do a replace on the commas to ad a space after each comma. You can do a replace on the last comma in colors with " and".