私のデータベースは次のようになります。
[foods]
foods_id, foods_name, groups_id, producers_id
[producers]
producers_id, producers_name
[groups]
groups_id, groups_name
PHP:
<?php
$producers = mysql_query('SELECT p.producers_name,p.producers_id FROM foods as f,producers as p WHERE p.producers_id = f.producers_id AND f.groups_id = 1 GROUP BY p.producers_name');
//list the producer...
while($row = mysql_fetch_array($producers, MYSQL_ASSOC)){
$foods = mysql_query('SELECT foods_id, foods_name FROM foods WHERE producers_id = '.$row['producers_id'].' ORDER BY foods_name ASC');
while($row2 = mysql_fetch_array($foods, MYSQL_ASSOC)){
//list the foods under this producer...
}
}
?>
ゴール:
PRODUCER A
FOOD A
FOOD B
FOOD C
PRODUCER B
FOOD D
FOOD E
PRODUCER C
FOOD F
...
解決:
<?php
$res = mysql_query('SELECT f.foods_id, f.foods_name, p.producers_id, p.producers_name FROM foods f, producers p WHERE p.producers_id = f.producers_id AND f.groups_id = '.$_GET['g'].' ORDER BY p.producers_name ASC, f.foods_name ASC');
$xproducers = array();
while($row = mysql_fetch_array($res , MYSQL_ASSOC)){
if(!array_key_exists($row['producers_id'],$xproducers)){
$xproducers[$row['producers_id']] = array('id'=>$row['producers_id'],'name'=>$row['producers_name'],'foods'=>array());
}
array_push($xproducers[$row['producers_id']]['foods'],array('id'=>$row['foods_id'],'name'=>$row['foods_name']));
}
?>
このソリューションは私にとって十分に高速です。おそらく完璧ではないかもしれませんが、うまく機能します:)素晴らしい助けをありがとうございました!
乾杯