![](/img/trans.png)
[英]How to get all matching records respectievelijk from MySql database using php which is stored in an array?
[英]Get all(one to many) records belongs to a user as an array from mysql using php
我有一張桌子,如下
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']);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.