PHP MySQL连接表为JSON

时间:2016-11-26 13:51:47

标签: php mysql json

我有两个不同的表 - 一个称为“产品”,其中包含有关在线商店的产品信息,另一个表称为“图像”,其中包含相应的产品图像(每个产品有几个图像)。 我想在主表“products”上加入表“images”,并以JSON格式输出结果。

表“products”如下所示(简化):

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"}]
}]

2 个答案:

答案 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

答案 1 :(得分:-1)

将JSON解码为Array并合并它们,然后再编译为JSON。尝试一下

两个功能:

array_merge($array1, $array2)

json_encode()