【发布时间】:2015-09-01 05:58:48
【问题描述】:
我找不到适合我的问题的标题。我正在做一个 Restful API /JSON
我的问题是:
我有两张桌子:
Product: id, name
Prices: id_product, price
Product 1--* Prices (One product have got multiples prices)
所以,如果我想以 JSON 格式导出下一个信息
products: [
{
id:1
name: chair
prices: [3.3,5.0,6.0]
}
, {
id:2
name: apple
prices: [2.0,5.0]
} ,..
]
我做下一个查询:
SELECT product.id, product.name, prices.price FROM procut LEFT JOIN prices ON product.id = prices.id_product
我得到了下一个结果:
id , name , prices
----------------------
1 chair 3.3
1 chair 5.0
1 chair 6.0
2 apple ...
...
我使用 PHP,codeigniter。有没有办法以良好的 JSON 格式进行转换?因为我必须重建结果,所以:
$resultArray = $query->result_array(); //CodeIgniter
foreach($resultArray as $row)
{
if(!isset($resultData[$row['id']]))
{
$resultData[$row['id']] = $row;
unset($resultData[$row['id']]['price']);
$resultData[$row['id']]['prices'] = array();
}
$resultData[$row['id']]['prices'][] = $row['price'];
}
创建格式良好的 JSON
【问题讨论】:
-
不知道你的意思?把你的数组写成
$this->output ->set_content_type('application/json') ->set_output(json_encode($resultData)); -
是的,我可以这样做,但是我将输出五个对象 Json(在这种特殊情况下),因为每一行都是一个对象 json。而且我只有两个(在我的示例中),因此我必须在 json 编码输出之前构建我的对象 json
标签: php mysql json codeigniter join