[0] => Array
(
[food_id] => 33
[food_category_id] => 51
)
[1] => Array
(
[food_id] => 33
[food_category_id] => 12
)
[2] => Array
(
[food_id] => 34
[food_category_id] => 62
)
[3] => Array
(
[food_id] => 35
[food_category_id] => 2
)
[4] => Array
(
[food_id] => 35
[food_category_id] => 80
)
[5] => Array
(
[food_id] => 35
[food_category_id] => 99
)
这是生成数组的查询
$query = $this->writedb->query("SELECT * FROM `food_to_category` WHERE food_id IN ( " . $implode_data . " )");
上面是输出,但是如果food_id相同,如何将数组组合成1个数组?现在显示的是所有独立数组,如果food_id相同,想合并
答案 0 :(得分:3)
您可以使用GROUP BY语句轻松完成此操作,但还必须使用GROUP CONCAT来保存所有类别ID
https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html
"SELECT food_id, GROUP_CONCAT(food_category_id) FROM `food_to_category` WHERE food_id IN ( " . $implode_data . " ) GROUP BY food_id"
我会产生相似的结果
[3] => Array
(
[food_id] => 35
[food_category_id] => "2,80,99"
)
如果要将类别ID作为数组,则可以用逗号将其爆炸