如何使用laravel或mysql创建嵌套的json?

时间:2015-04-01 10:08:29

标签: mysql json laravel nested

我需要这样的事情:

  "results":[  
  {  
     "id":1,
     "date":{  
        "date":"2015-04-1 00:00:00.000000",
        "timezone_type":3,
        "timezone":"America\/Denver"
     }
  },

查询:

$find = DB::select( DB::raw("SELECT created_at as date, 'America/Denver' as timezone, 3 as timezone_type FROM table"));
return Response::json($find);

如何使用mysql / Laravel在日期内创建日期?我尝试使用array_merge但是date会被附加在底部而不是make本身嵌套。

1 个答案:

答案 0 :(得分:3)

只需将代码更改为以下代码:

        $tableIds = DB::select( DB::raw("SELECT id FROM table"));
        $jsonResult = array();

        for($i = 0;$i < count($tableIds);$i++)
        {
            $jsonResult[$i]["id"] = $tableIds[$i]->id;
            $id = $tableIds[$i]->id;
            $jsonResult[$i]["date"] = DB::select( DB::raw("SELECT created_at as date, 'America/Denver' as timezone, 3 as timezone_type  FROM table WHERE id = $id"));
        }

        return Response::json(array(
                    'error'     =>  false,
                    'stores'    =>  $jsonResult),
                    200
            );