簡體   English   中英

使用PHP從MySQL獲取所有(一對多)記錄屬於用戶的數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM