获取统计数据并在图表中显示- PHP/HighCharts

Get stats and show it in chart - PHP/HighCharts

本文关键字:显示 PHP HighCharts 统计数据 获取      更新时间:2023-09-26

我有一个名为"tracks"的表,它看起来像这样:

  1. id,
  2. ,
  3. li>点击

我有一个饼状图,来自highcharts,代码看起来像这样:

 var chart;
$(document).ready(function() {
   chart = new Highcharts.Chart({
      chart: {
         renderTo: 'chart',
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: false
      },
      title: {
         text: 'Where users came from, total'
      },
      tooltip: {
         formatter: function() {
            return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
         }
      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
               enabled: false
            },
            showInLegend: true
         }
      },
      credits: {
        enabled: false
      },
       series: [{
         type: 'pie',
         name: 'Browser share',
         data: [
            ['Firefox.com',   45.0],
            ['Default.com',       26.8],
            ['MSN',       12.8],
            ['Google.com',    8.5],
            ['Yahoo.com',     6.2],
            ['Others',   0.7]
         ]
      }]
   });
});

我的问题是,我如何从"tracks"表(hits)和(name)中获取数据并将其输出到饼状图中,如:

"名称","打"

然后,最后,将# of hits转换为%。

 series: [{
         type: 'pie',
         name: 'Browser share',
         data: [
         <?php
         $sql = 'select sum(hits) from tracks';
         $result = mysql_query($sql);
         $row = mysql_fetch_row($result);
         $totalHits = $row[0];
         $sql = 'select name, hits from tracks order by hits desc';
         $result = mysql_query($sql);
         $i = 0;
         $totalOther = 0;
         $maxSlices = 5;
         $minPercent = 10;
         while ($row = mysql_fetch_row($result))
         {
            $percent = row[1] / $totalHits * 100;
            if (++$i <= $maxSlices && $percent >= $minPercent)
            {
                echo json_encode($row);
            }
            else
            {
                $totalOther += $row[1];
            }
         }
         if ( $totalOther > 0 ) echo json_encode(array('Other', $totalOther));
         ?>
         ]
      }]

如果你想通过ajax刷新它…

...
series: [{
         type: 'pie',
         name: 'Browser share',
         data: getData(function(result) {return result;}),
...

function getData(setDataCallback)
{
    $.getJSON('file.php', args, function(result)  {  // use of jquery for clarity.
        setDataCallback(result);
    });
}

在PHP中,您必须使用第一个代码块中显示的代码创建一个新文件('file. PHP ');

最简单的方法是从mySql中查询数据,然后像

一样排序
[
        ['Firefox.com',   45.0],
        ['Default.com',       26.8],
        ['MSN',       12.8],
        ['Google.com',    8.5],
        ['Yahoo.com',     6.2],
        ['Others',   0.7]
     ]

需要,如果你想显示图表只是在页面加载。