检索数据从mongodb和链接它与谷歌图表

retrieve data from mongodb and link it with google charts

本文关键字:谷歌 链接 数据 mongodb 检索      更新时间:2023-09-26

我想从数据库(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>

您在PHP中有一个语法错误,即使修复了这个错误,您的数据结构也不完全适合visualapi。试试这个:

$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数组和对象,而不用担心数组和对象构造的语法。