我想从数据库(mongodb)中检索数据,并且我想使用谷歌图表绘制饼图。 在第一种情况下,我有一个名为user的集合,每个用户都有一个名为(付费)的布尔属性,我想计算有多少付费用户和免费用户,并根据这些结果我将绘制一个饼图与百分比各种用户
这是我尝试了很长一段时间,但我不会到达显示图表,
谢谢:)
<?php
$connection = new MongoClient();
$collection = $connection->pato->user;
$cursor = $collection->find();
$cursor = $collection->find(array("paid"=>true));
$x=$cursor->count();
$cursor = $collection->find(array("paid"=>false));
$y=$cursor->count();
$myurl[]="['Option','Value']";
$myurl[]=[['Free users', $y],['Paid users', $x]];
?>
<html>
<head>
<!--Load the AJAX API-->
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
// Set chart options
var options = {'title':'User statistics',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('userStatsDiv'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}</script>
<body>
<div id="usageStatsDiv" style="width:700; height:500"></div>
</body>
</html>
答案 0 :(得分:0)
您在PHP中存在语法错误,甚至修复它,您的数据结构不适合Visualization API。试试这个:
$myurl = array(
array('Option', 'Value'),
array('Free users', $y),
array('Paid users', $x)
);
然后在javascript中:
var data = google.visualization.arrayToDataTable(<?php echo json_encode($myurl, JSON_NUMERIC_CHECK); ?>);
使用json_encode
允许您从PHP数组转换为javascript数组和对象,而无需担心数组和对象构造的语法。