我正在努力将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]
]);


我只是不知道出了什么问题。任何帮助表示赞赏。

最佳答案

Dinesh给出的答案有效:

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

09-28 02:55