PHP MYSQL INNER加入JSON

时间:2015-04-10 05:57:57

标签: php mysql json

我有两张桌子,

第一个:表产品表产品

| id | name   | code |
| 1  | blouse | AB1  |
| 2  | jeans  | BA2  |
| 3  | dress  | C61  |

和第二个表格颜色表格颜色

| id_product | colors | amount |
|     1      | blue  |  50    |
|     1      | red   |  40    |
|     1      | yellow|  10    |
|     2      | white |  15    |
|     2      | blue  |  60    |
|     3      | purple|  110   |

查询:我的查询php

.../blabla
SELECT product.id, product.name, product.code,color.id_product, color.colors, color.amount
FROM product
INNER JOIN color 
ON product.id = color.id_product limit 1

while($query)) {
    $var[] = $query;
}
echo '{"status":'. json_encode($var).'}';

输出:

{
    "status":{
        "1":{
            "id":"1",
            "code":"blouse",
            "id_product":"1",
            "colors":"blue",
            "amount":"50",
        }
    }
}

我想要的JSON是这样的:

{
    "status":{ 
        "1":{  
            "id":"1",
            "code":"blouse",
            "id_product":"1",
            "colors":"blue",
            "amount":"50",
            "id_product":"1",
            "colors":"red",
            "amount":"40",
            "id_product":"1",
            "colors":"yellow",
            "amount":"10",
        }
    }
}

将颜色变成一个数组json,这可能吗?

2 个答案:

答案 0 :(得分:2)

所以你应该使用group_concat将它们放入一个列表中,然后在编码为json之前使用PHP来爆炸列表。

SQL小提琴

http://sqlfiddle.com/#!9/ba3b8/3

SELECT product.id, product.name, product.code,
color.id_product, color.colors, color.amount,
group_concat(color.colors) as clist,
group_concat(color.amount) as alist

from product, color
where product.id = color.id_product
group by color.id_product

然后在你的PHP中你需要遍历结果,使用explode将列表转换为数组并根据需要将数据插入到结果中使用json_encode();

答案 1 :(得分:0)

您应该使用此查询:

SELECT product.id, product.name, product.code
color.id_product, color.colors, color.amount
from product
INNER JOIN color 
ON product.id = color.id_product
where product.id=1

LIMIT会给你一条记录。