我正在试图弄清楚如何创建一个嵌套的JSON对象,如下所示:
company: "Company 1",
pricing: {
term: "1 year",
price: "$4.95",
term: "2 years",
price: "3.95"
},
我在MySQL中有两个表,一个名为以这种方式构建的计划
| id | company |
------------------
| 2 | company 1 |
和另一个表plans_pricing来表示定价数据
| id | plans_id | term | price |
--------------------------------
| 1 | 2 | 1 year | $4.95 |
| 2 | 2 | 2 years| $3.95 |
我使用Laravel 4查询数据库并创建json以发送回我的ajax请求。这是查询,当前发送服务器500错误。
public function results()
{
$answers = $_POST['answers'];
$data = DB::table('plans')
->join('plans_pricing', 'plans.id', '=', 'plans_pricing.plans_id')
->select('plans.company', 'plans_pricing.price', 'plans_pricing.term')
->whereIn('plans.id', $answers)
->get();
echo json_encode($data);
}
我不确定为什么这个查询不起作用,但这甚至不是我问这个问题的原因。我需要知道如何获得嵌套的JSON对象,当我创建连接时,我相信我会收到一个单独的对象,就像这里:
| company | price | term |
------------------------------------
| company 1 | 4.95 | 1 year |
| company 1 | 3.95 | 2 years|
如何让这个SQL查询返回一个嵌套的JSON对象,就像我上面描述的那样?我已经坚持这个问题两天了,真的可以使用一些指导。谢谢
更新:
通过将echo json_encode
更改为return Response::json($data);
答案 0 :(得分:3)
我从未使用过Laravel,但我认为应该工作:
$output = array();
$currentCompany = "";
foreach ($data as $datum) {
if ($datum->company != $currentCompany) {
$output[] = array();
// get a reference to the newly added array element
end($output);
$currentItem = & $output[key($output)];
$currentCompany = $datum->company;
$currentItem['company'] = $currentCompany;
$currentItem['rates'] = array();
}
$currentItem['rates'][] = array("price" => $datum->price, "term" => $datum->term);
}
json_encoded结果:
[{
"company":"company 1",
"rates":[{
"price":4.95,"term":"1 year"
},{
"price":3.95,"term":"2 years"
}]
}]