简体   繁体   English

使用PHP从MySQL获取所有(一对多)记录属于用户的数组

[英]Get all(one to many) records belongs to a user as an array from mysql using php

I have a table as below 我有一张桌子,如下

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

Required output using PHP is 使用PHP所需的输出是

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

One solution could be get all result from mysql & then run a foreach on it like this 一种解决方案可以从mysql获取所有结果,然后像这样对它运行foreach

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

But is there any other optimal way of doing it? 但是还有其他最佳方法吗?

Use GROUP_CONCAT() function for this. 为此使用GROUP_CONCAT()函数。

Here's the reference: 这是参考:

So your query should be like this: 因此,您的查询应如下所示:

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

Output: 输出:

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

Edited: 编辑:

// 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']);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM