dsfliu1129 2014-05-28 14:09
浏览 103
已采纳

返回正确格式化的json响应,以便在Laravel的highcharts中使用

I have a highcharts chart in one of my views and I want the source data to be ajax loaded from a route that returns a json response.

So I made an api route:

Route::get('api/v1/data/{id}', function($id) {
    //Do some stuff and make a key value array with unix timestamp as key and float as value
    $data = Model::getData($id);    
    return $data;
});

I have set up the highchart in my view as in the demo but with my api route as the json source. My chart renders OK but the data is not drawn. There are no errors in the console.

When I view the output of my api route the json output is as follows:

{
    "1317423600": 0,
    "1325289600": -0.17099521359192,
    "1333148400": 0.85133638321359,
    "1341010800": -0.94235521748172,
    "1348959600": 0.37334056741349,
    "1356912000": -0.15089107586321,
    "1364688000": 10.261663055542,
    "1372546800": 9.4860565407533,
    "1380495600": 6.2120398914028,
    "1388448000": 8.7469537358921,
    "1396220400": 8.7985530414845,
    "1398812400": 7.633928980909
}

While the demo json output is like this:

[
  [1147651200000,67.79],
  [1147737600000,64.98],
  [1147824000000,65.26],
  [1147910400000,63.18],
  [1147996800000,64.51],
  [1148256000000,63.38],
  [1148342400000,63.15]
]

I suspect this is why the data is not rendering. Why the difference in output and how can I return a response that highcharts will understand.

  • 写回答

2条回答 默认 最新

  • doushifen4060 2014-05-28 14:34
    关注

    It looks like the problem is with the data source (model data result).

    Check this out, if you prepared the data like this:

    $data[] = array(1317423600,0);
    $data[] = array(1325289600, -0.17099521359192);
    $data[] = array(1333148400, 0.85133638321359);
    
    var_dump(json_encode($data));
    

    it produces the json in the format you want:

    string '[[1317423600,0],[1325289600,-0.17099521359192],[1333148400,0.85133638321359]]' (length=77)
    

    So... to fix this, can could try something like this:

    Route::get('api/v1/data/{id}', function($id)
    {
        // Load DB Data
        $data = Model::getData($id);    
    
        // Parse Data
        $parsedData = array();
        foreach ($data as $k => $v)
            $parsedData[] = array($k, $v);
    
        // Finish
        return $parsedData;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料