我尝试使用Google Chart API使用数据库中的数据创建饼图。我的数据库有两列,一个是ID,一个是主要的。对于行,我有相应的ID和一些专业。我使用PHP来累计每个专业,然后将其转换为JSON。我的数据在JSON中看起来格式正确,但由于某种原因,饼图只显示MAJOR并且数字为2(100%)。它似乎没有正确阅读大公司的总数,我不明白为什么。我已经做了一些搜索,但找不到有类似问题的人。
这是输出的JSON
{"cols":[{"label":"Major","type":"string"},{"label":"CS","type":"number"},{"label":"CIS","type":"number"},{"label":"Other","type":"number"}],"rows":[{"c":[{"v":"MAJOR"},{"v":2},{"v":1},{"v":2}]}]}
这是我的PHP
$db = new PDO("mysql:host=".$servername.";dbname=".$dbname.";", $username, $password);
$query = $db->query("SELECT 'MAJOR' as 'Major', SUM(IF(MAJOR = 'Computer Science',1,0)) as CS, SUM(IF(MAJOR = 'Computer Information Systems',1,0)) as CIS, SUM(IF(MAJOR = 'Other',1,0)) as Other FROM ages");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Major', 'type' => 'string'),
array('label' => 'CS', 'type' => 'number'),
array('label' => 'CIS', 'type' => 'number'),
array('label' => 'Other', 'type' => 'number')
);
while($r = $query->fetch()){
$temp = array();
$temp[] = array('v' => $r['Major']);
$temp[] = array('v' => (int) $r['CS']);
$temp[] = array('v' => (int) $r['CIS']);
$temp[] = array('v' => (int) $r['Other']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
这里是加载图表并使用JSON数据的Javascript
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}