Sankey图无法使用json输出传递

时间:2018-07-17 04:36:24

标签: highcharts sankey-diagram

使用数据库中的数据,我试图模拟sankey图working JSFiddle.

我正在使用下面的代码

组装数据
// sdata.php
<?php
$con = sqlsrv_connect($server, $options);
if (!$con){die('Could not connect: ' . sqlsrv_error());}
$sql_query = "select * from test_data";
$result = sqlsrv_query($con, $sql_query);
$series = array(); 
$series['type'] = 'sankey'; 
$series['name'] = 'Gendata'; 
$series['keys'] = '[\'from\',\'to\',\'weight\']'; 

while($r = sqlsrv_fetch_array($result)) 
{ 
$series1 = array(); 
$series1[] = $r['PARENT']; 
$series1[] = $r['CHILD']; 
$series1[] = $r['DGEN'];
$series['data'][] = $series1;
}
$result = array(); 
array_push($result,$series); 
print json_encode($result, JSON_NUMERIC_CHECK); 
sqlsrv_close($con);
?>


我的JSON看起来像

    [{
   "type":"sankey",
   "name":"Gendata",
   "keys":"['from','to','weight']",
   "data":[
      ["GROUP","COAL",24.46], ["GROUP","GAS",11.96],["GROUP","HYDRO",19.36],
      ["HYDRO","HYD",19.36], ["COAL","ER2",22.4],["GAS","NR",19]
          ]
    }]

我的图表借出代码如下

$(document).ready(function() {  
var options = {
          chart: {
           renderTo: 'container',
            showAxes: true
                 },
          yAxis: [{
            lineWidth: 1,
            tickPositions: [0, 1, 2, 3]
                 }],
          title: {
                text: 'Sankey Diagram'
                 },
          series: []
}
$.getJSON("sdata.php", function(resp) {
 console.log(resp);
 options.series[0] = resp[1]; //option 1 to assign the data in series
 //options.series.push.resp; //option 2 to push the data in series
 chart = new Highcharts.Chart(options);
});
});

但是我失败了。我找不到我所缺少的错误
请帮助我。

让我知道我是否可以提供进一步的信息。

1 个答案:

答案 0 :(得分:0)

从您在此处发布的代码来看,错误是您的keys分配。

您有:

"keys":"['from','to','weight']",

但是它必须是:

"keys": ['from','to','weight'],

也就是说,数组不应该用引号引起来,因为这样它将被解释为字符串。

在您的PHP中,这意味着:

$series['keys'] = '[\'from\',\'to\',\'weight\']'; 

需要为:

$series['keys'] = ['from', 'to', 'weight']; 

工作示例: https://jsfiddle.net/ewolden/aeh02djx/