从 SQL 结果创建嵌套的 JSON 对象
Creating a nested JSON object from SQL results
我正在尝试弄清楚如何创建一个嵌套的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);
来修复服务器 500 错误
我从未使用过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"
}]
}]
相关文章:
- jQuery匹配JSON对象的部分文本
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 如何为json对象中的段发送array[]
- 将JSON对象传递给angular指令
- 更改JSON对象的结构
- 访问JSON对象内部的数组元素
- 在ejs-partial中对JSON对象进行迭代
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 访问嵌套JSON对象的键,其中键是动态的
- json对象中缺少对象循环
- 发送json对象或使用express路由呈现视图
- 在play2框架中向json对象添加下拉列表项
- 元素名称上带有短划线 (-) 字符的 Json 对象
- autocomplete不接受源的json对象
- 如何在javascript中创建动态json对象
- 在使用客户端脚本时拾取JSON对象
- 如何通过json对象数组为嵌套对象赋值
- 构造JSON对象