gpt4 book ai didi

php - 我如何在 PHP 而不是 MySQL 中进行 groupby 或 groupconcat ?

转载 作者:行者123 更新时间:2023-11-29 14:03:41 24 4
gpt4 key购买 nike

我有一个 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.

有没有一种方法可以执行相同的 group by 和 group_concact 逻辑,而不是在 sql 语句中执行 Group by 和 Group_Concat 并处理爆炸等来处理分隔符并将其放入 php 数组中在 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; ?>

最佳答案

如果你想保持 SQL 那样,为什么不在 PHP 中做这样的事情:

  while($row = dbOBj->Fetch($result))
{
$meal[$row['meal desc'][] = $row['food desc'];
}

你最终会得到$meal['Meal 1'] = array('egg', 'eggwhites', ...)

关于php - 我如何在 PHP 而不是 MySQL 中进行 groupby 或 groupconcat ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com