我试图通过使用谷歌图表以折线图的形式显示mysql数据。我认为问题是我试图格式化谷歌图表的数据时的部分。我的代码出了什么问题?
$sth = mysql_query("SELECT * FROM real_price");
$data = array (
'cols' => array(
array('id' => 'period', 'label' => 'Period', 'type' => 'string'),
array('id' => 'demand', 'label' => 'Demand(MW)', 'type' => 'number')
),
'rows' => array();
);
while ($res = mysql_fetch_assoc($sth)){
$data['rows'][] = array('c' => array(
array('v' => $res['Period']),
array('v' => $res['Demand(MW)'])
));
}
$json = json_encode($data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable(<?php echo $json ?>);
var options = {
title: 'Price information'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
答案 0 :(得分:0)
我认为json格式错误,应该是
$sth = mysql_query("SELECT * FROM real_price");
$data = array(array("Period", "Demand(MW)"));
while ($res = mysql_fetch_assoc($sth)){
$data[] = array($res['Period'], $res['Demand(MW)']);
}
$json = json_encode($data);