从mongodb检索数据并使用Google图表将其可视化

retrieve data from mongodb and visualize it with google charts

本文关键字:可视化 Google 检索 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>

我认为你的问题是你的JSON:

var data=google.visualization.arrayToDataTable([
    <?echo(implode(",",$myurl));?>
]);

看起来你试图自己构建JSON字符串。让PHP代替你做这些工作——使用json_encode代替,像这样:

var data=google.visualization.arrayToDataTable([
    <?php echo json_encode($data); ?>
]);

您需要构建您的$data数组,以便它为您提供正确的元素,但我认为您会发现最终结果更清晰,更容易理解。