我的数据库看起来像这样:
[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']));
}
?>
这个解决方案对我来说已经足够快了,也许它并不完美,但它做得很好:) 感谢大家的大力帮助!
干杯