我有一个 SQL 查询:
SELECT mealdesc, group_concat(fooddesc) as fooddesc
FROM plan p
INNER JOIN mealplan mp
ON mp.planid = p.id
INNER JOIN meal m
ON m.id = mp.mealid
INNER JOIN foodmeal fm
ON fm.mealid = m.id
INNER JOIN food f
ON f.id = fm.foodid
where userid = 2
GROUP by mealdesc
order by mealdesc
结果如下所示:
mealdesc,fooddesc
Meal 1,"egg,egg whites,oatmeal,wheat toast,fruit,berries"
Meal 2,"Isolyze,raw nuts"
Meal 3,"chicken,turkey,yam,baked potato,veggies,medium salad"
Meal 4,"Isolyze,raw nuts"
Meal 5,"veggies,lean red meat,salmon,Chilean Sea Bass,large salad"
Meal 6,"veggies,large salad,Casein Protein,white fish"
当我删除 group by 和 group_concat 结果如下所示:
mealdesc,fooddesc
Meal 1,egg
Meal 1,egg whites
Meal 1,oatmeal
Meal 1,wheat toast
Meal 1,fruit
Meal 1,berries
Meal 2,Isolyze
Meal 2,raw nuts
Meal 3,veggies
Meal 3,medium salad
Meal 3,chicken
Meal 3,turkey
...and so on.
与其在 sql 语句中执行 Group by 和 Group_Concat 并且必须处理爆炸等来处理分隔符并将其放入 php 数组中,有没有办法执行相同的 group by 和 group_concact 逻辑并组织所有这些在 PHP 中并将其推入数组?
更新:感谢您到目前为止的回复。将我的 PHP 和 HTML 部分添加到此。
我基本上希望将每餐输出为标题,并将每种食物输出为列表。我过去使用过explode,但我无法正确形成数组,也许这只是我的问题。
PHP代码:
$sql = "SELECT mealdesc, group_concat(fooddesc) as fooddesc
FROM plan p
INNER JOIN mealplan mp
ON mp.planid = p.id
INNER JOIN meal m
ON m.id = mp.mealid
INNER JOIN foodmeal fm
ON fm.mealid = m.id
INNER JOIN food f
ON f.id = fm.foodid
where userid = 2
GROUP by mealdesc
order by mealdesc";
$result = mysqli_query($link, $sql);
if (!$result)
{
echo 'Error';
exit();
}
// Fetch food data
while($row = mysqli_fetch_assoc($result)){
$meals[] = array('mealdesc' => $row['mealdesc'], 'fooddesc' => explode(",", $row['fooddesc']));
}
echo '<pre>';
echo print_r($meals, true);
echo '</pre>';
然后在我的 HTML 中,我像这样循环输出膳食和食物描述
<?php foreach ($meals as $meal): ?>
<h4><?php htmlout($meal['mealdesc']); ?></h4>
<ul>
<li><?php htmlout($meal['fooddesc']); ?></li>
</ul>
<?php endforeach; ?>