gpt4 book ai didi

php - 使用php从mysql获取属于用户的所有(一对多)记录作为数组

转载 作者:行者123 更新时间:2023-11-29 11:46:50 25 4
gpt4 key购买 nike

我有一个表格如下

user    category
1 157
1 158
2 158
2 159
3 157

使用 PHP 所需的输出是

[
1 => [157,158],
2 => [158,159],
3 => [157]
]

一个解决方案可以从 mysql 获取所有结果,然后像这样运行 foreach

foreach ($result as $row) {
$finalResult[$row['user']][] = $row['category'];
}

但是还有其他最佳方法吗?

最佳答案

为此使用GROUP_CONCAT()函数。

引用资料如下:

所以你的查询应该是这样的:

SELECT user, GROUP_CONCAT(category SEPARATOR ',') AS categories FROM your_table GROUP BY user; 

输出:

+------+------------+
| user | categories |
---------------------
| 1 | 157,158 |
---------------------
| 2 | 158,159 |
---------------------
| 3 | 157 |
+-------------------+

已编辑:

// suppose $conn is your connection handler

$finalResult= array();
$query = "SELECT user, GROUP_CONCAT(category SEPARATOR ',') AS categories FROM your_table GROUP BY user";

if ($result = $conn->query($query)) {

while ($row = $result->fetch_assoc()) {
$finalResult[$row['user']] = explode(",", $row['categories']);
}

}

关于php - 使用php从mysql获取属于用户的所有(一对多)记录作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34787095/

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