接收PHP数组的AddRows

时间:2015-02-04 23:27:12

标签: javascript php arrays google-visualization

我正在努力将PHP中的数据转换为图表。我在1个php页面上有以下代码片段。首先是简单的部分:

$sql = "SELECT * FROM (SELECT timestamp, CurrentKelvin, TargetKelvin, WeatherTempKelvin FROM  `rawdata` ORDER BY  `rawdata`.`timestamp` DESC LIMIT 10) AS ttbl ORDER BY `timestamp` ASC;";
$results = mysqli_query($con,$sql);
$ChartData = array();
    foreach($results as $result) 
    { 
        $ChartData[] = array( (int)$result['CurrentKelvin'],(int)$result['TargetKelvin']);
    }
    $ChartData = json_encode($ChartData);

然后是javascript部分:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load('visualization', '1.0', {'packages':['corechart']});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'CurrentKelvin');
      data.addColumn('number', 'TargetKelvin');
      alert( <?php echo json_encode($ChartData); ?>);

      data.addRows( <?php echo json_encode($ChartData); ?> );
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data);
    }
</script>

<!--Div that will hold the pie chart-->
<div id="chart_div"></div>

当我运行以上命令时,alert命令显示以下输出:

[[292,290],[292,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290]]

但data.addRows行会生成以下错误: 错误:给予addRows的参数必须是数字或数组

将data.addRows更改为简单的东西(并将data.addColumn更改为字符串,使用相同的数组结构,我得到一个图表:

data.addRows([
  ['Ivan', 5],
  ['Igor', 7],
  ['Felix', 8],
  ['Bob', 4] 
]);

我无法弄清楚出了什么问题。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

Dinesh给出的答案工作:

      var json_arr = <?php echo json_encode($ChartData); ?>; 
      data.addRows(JSON.parse(json_arr));