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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵