javascript - while 循环使用谷歌图表

标签 javascript php html mysql

所以我遇到了这个问题,我从数据库中提取页面上的点击次数。当数据库中只有一个国家时,饼图工作得很好,现在有几个国家,但它从前 5 个国家中抓取。它工作得很好,但我认为我的 while 循环搞砸了,我该如何重新格式化它才能工作? `

数据库查询:

$csel = $odb->query("SELECT country, COUNT(*) AS cnt FROM bots GROUP BY country ORDER BY cnt DESC LIMIT 5");

显示:

     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Country', 'Total Bots'],
          <?php
  while ($c = $csel->fetch())
                                    {
                    $top2 = geoip_country_name_by_id($gi, $c[0]);
                    $top = number_format($c[1]);
                                        echo ("['$top2', '$top']");

  }

我认为这是因为我在 echo 末尾没有逗号,所以我尝试了,饼图是灰色的,并显示“其他”

我想我需要以某种方式制作一个字符串来执行 echo 所说的操作,并添加一个逗号直到最后一个数据。

有人可以帮我解决这个问题吗?

最佳答案

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
        ['time', 'Price'],
          <?php  while ($r = mysqli_fetch_array($res)) { 
                echo "[' ".$r["timestamp"]." ', ".$r["totalprice"]." ],";
          } ?>  
    ]);

    var options = {
      title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
</script>

关于javascript - while 循环使用谷歌图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554656/

相关文章:

html - 如何并排对齐两个表格?

javascript - 生成只有一列的表

javascript - Firebase - JS 查询 - 获取一个节点,其中子值具有值为 xxx 的子节点

javascript - typescript 中的对象解构

javascript - SOP(同源策略)的含义

phpcs - 防止显示 "Opening parenthesis of a multi-line function call must be the last content on the line"

javascript - 使用 javascript 比较 2 个 ASCII 字符

PHP 正则表达式搜索包含,然后在找到它们的地方写入包含

php - 数字作为php中的变量名

javascript - 打开新页面时保持弹出窗口打开