我正在尝试使用他们的 API 创建一个简单的谷歌折线图。硬编码,这有效:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2010', 1000.31],
['2011', 1170.68],
['2012', 660]
]);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
但是,我正在尝试使用 MySQL 中的数据填充图表值。我怎样才能让它工作?
$arr = array('Year' => 'Sales', '2010' => 1000.31, '2011' => 1170.68, '2012' => 660);
$chart_data = json_encode($arr);
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable(<?php echo $chart_data ?>);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
基本上,我正在从 MySQL 结果创建一个 PHP 数组,并尝试在 Google 图表中显示其内容。