2016-11-26 37 views
3

我有兩個不同的表格 - 一個名爲「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"}] 
}] 
+1

你是如何獲取當前的JSON輸出?這是來自MySQL還是PHP? –

+0

'WHERE listorder = 1'限制它爲每個產品的一個圖像 – cske

+0

最有可能手動我認爲 你將不得不使你的數組​​和json編碼,我認爲使用多個查詢 – Buddhi741

回答

-1

將JSON解碼爲數組併合並它們,然後再次編碼爲JSON。嘗試做

兩個功能:

array_merge($array1, $array2)

json_encode()

+0

謝謝你的答案 - 雖然它通常是有用的鏈接到在線其他地方的文檔,如果您可以用一些代碼演示如何使用這些函數來處理原始問題,那麼這也會非常有幫助。 –

1
SELECT 
    p.id as p_id, 
    p.name as p_name, 
    group_concat(concat('{"img_id":"',i.img_id,'"img":"',i.img,'"}') separator ',') as img 
FROM products p 
    JOIN (SELECT * FROM images WHERE listorder=1) 
    AS i ON (i.p_id = p.id) 
GROUP BY p.id,p.name