簡體   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