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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分