繁体   English   中英

从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 |

和另一个表plan_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来修复服务器500错误以return Response::json($data);

我从未使用过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"
    }]
}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM