我有兩個不同的表格 - 一個名爲「products」,其中包含有關網上商店產品的信息,另一個名爲「images」,其中包含各個產品圖像(每個產品的幾個圖像)。 我想加入主表「products」上的表格「images」並以JSON格式輸出結果。PHP MySQL連接表格爲JSON
表 「產品」 如下所示(簡化):
id | name
----|--------
57 | apple
58 | tomato
59 | ...
而表 「圖像」 爲產品圖片:
img_id | img | p_id | listorder
-------|-------------|------|----------
32 | apple1.jpg | 57 | 1
33 | apple2.jpg | 57 | 2
34 | tomato1.jpg | 58 | 1
35 | ... | ... | ...
到現在爲止,我的查詢是這樣的:
$sql = "SELECT
p.id as p_id,
p.name as p_name,
i.*
FROM products p
JOIN (SELECT * FROM images WHERE listorder=1)
AS i ON (i.p_id = p.id)";
因此,輸出(數據讀取到一個數組,並轉換到JSON後)看起來像第是:
[{
"id": "57",
"name": "apple",
"img": "apple1.jpg"
}, {
"id": "58",
"name": "tomato",
"img": "tomato1.jpg"
}]
所以我的問題是:如何輸出以下內容?
[{
"id": "57",
"name": "apple",
"img": [{"img_id": "32","img": "apple1.jpg"}, {"img_id": "33","img": "apple2.jpg"}]
}, {
"id": "58",
"name": "tomato",
"img": [{"img_id": "34","img": "tomato1.jpg"}]
}]
你是如何獲取當前的JSON輸出?這是來自MySQL還是PHP? –
'WHERE listorder = 1'限制它爲每個產品的一個圖像 – cske
最有可能手動我認爲 你將不得不使你的數組和json編碼,我認爲使用多個查詢 – Buddhi741