Google 来自自定义 mysqli 查询的饼图

Google Pie charts from custom mysqli query

我正在尝试使用 php、mysqli 来实现 google 图表。我想为 Lesson-Activity 制作一个包含 3 个切片的饼图,3 个切片是三列:计数(<50%)、计数(50-60% 之间)、计数(>60%)。我尝试使用不同的程序进行搜索,从我的角度尝试了不同的可能性,但无法满足这种要求。我无法在我的代码中添加两个以上的列。

要求:我正在寻找一个 lesson_activity 显示所有三列的饼图:cond1、cond2 和 cond3(在一个饼图中)。

我来到 stack overflow 是为了与高素质的开发人员分享我的代码。

请分享您的建议。

TABLE : lesson_grades

id            lesson           lesson_activity   count(<50%)   count(Between 50-60%)   count(>60%)
5      Community Health Care        CHC.001            9                 7                   2
5      Community Health Care        CHC.002            2                 5                   6
5      Community Health Care        CHC.003            9                 2                   0
13     Spaceship                    SS.001             1                 13                  7
3      Risk Analysis                RA.001             1                 13                  7
3      Risk Analysis                RA.002             1                 9                   0
3      Risk Analysis                RA.003             1                 3                   4
3      Risk Analysis                RA.004             0                 7                   21
3      Risk Analysis                RA.005             0                 30                  11
15     Community Qualifications     CA.001             1                 13                  32

代码

<?php

  $DB_NAME = 'lessons';
  $DB_HOST = 'localhost';
  $DB_USER = '---';
  $DB_PASS = '---';

  $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

  if (mysqli_connect_errno()) 
  {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }
$sql = $mysqli->query('SELECT id, lesson, lesson_activity, count(<50%) AS cond1, count(Between 50-60%) AS cond2, count(>60%) AS cond3  FROM lesson_grades');

$rows = array();
$flag = true;

$table = array();

$table['cols'] = array(
  array('label' => 'lesson_activity', 'type' => 'string'),
  array('label' => 'cond1', 'type' => 'number'),
  array('label' => 'cond2', 'type' => 'number'),
  array('label' => 'cond3', 'type' => 'number'),
);

$rows = array();
while($r = mysqli_fetch_assoc($sql)) 
{
    $temp = array();
    $temp[] = array('v' => (string) $r['lesson_activity']); 
    $temp[] = array('v' => $r['cond1'], $r['cond2'], $r['cond3']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;

?>

<html>
  <head>

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    google.load('visualization', '1', {'packages':['corechart']});

    google.setOnLoadCallback(drawChart);

    function drawChart() 
    {
      var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
      var options = 
      {
           title: 'My Weekly Plan',        
           legend: 'none',        
           slices: {0: {color: 'black'}, 1: {color: 'red'}} 
      };     
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
    </script>
  </head>
  <body><div id="piechart" style="width:500px;height:500px;"></div></body>   
  </html>

我相信有人会给你一个纯粹的 javascript 版本,但这里有一个 class 可以与 php 一起使用,它将自动生成 javascript如果你感兴趣。如果不是最底部的代码是要尝试的输出:

图书馆:

Update: https://github.com/rasclatt/PHP-to-Google-PieCharts-Converter

<?php
    class   GoogleCharts
        {
            public      $newArr;
            public      $VarName;
            public      $DataArray;
            public      $options;

            protected   $id;
            protected   $compiler;
            protected   $chartType;

            const   PIE     =   'pie';
            const   SCATTER =   'scatter';

            public  function __construct()
                {
                    $this->options      =   array("title"=>"Untitled");
                    $this->chartType    =   'pie';
                }

            function CreatePie($settings = false)
                {
                    if(!is_array($settings))
                        return;

                    $data           =   (!empty($settings['data']))? $settings['data']:false;
                    $this->id       =   (!empty($settings['id']))? $settings['id']:false;
                    $incr           =   (!empty($settings['incr']))? $settings['incr']:false;

                    $this->VarName  =   "";
                    $this->newArr   =   array();

                    if($data != false && $this->id != false) {
                            foreach($data as $key => $value) {
                                    $dvalue         =   (is_numeric($value))? $value:"'{$value}'";
                                    $key            =   (is_numeric($key))? $key:"'{$key}'";
                                    $this->newArr[] =   "\t\t\t\t\t[{$key}, {$dvalue}]";
                                }
                        }

                    $this->VarName  =   "DataSet{$incr}";

                    if(!empty($this->newArr)) {
                            $str    =   PHP_EOL."var {$this->VarName}   =   [".PHP_EOL;
                            $str    .=  implode(",".PHP_EOL,$this->newArr).PHP_EOL;
                            $str    .=  "\t\t\t\t]".PHP_EOL;
                        }

                    $this->DataArray    =   (!empty($str))? $str:false;

                    return $this;
                }

            public  function ChartData()
                {
                    $str    =   (!empty($this->DataArray))? $this->DataArray:"";
                    $str    .=  PHP_EOL;

                    return $str;
                }

            protected   function MakeJSObjects($arr)
                {
                    if(is_array($arr)) {            
                            foreach($arr as $k => $v) {
                                        $return[$k] =   $k.': '.$this->MakeJSObjects($v);
                                }
                        }
                    else {
                            $arr    =   (is_numeric($arr) || $arr === 'true' || $arr === 'false')? $arr: "'$arr'";
                            $return =   (strpos($arr,'{') !== false && strpos($arr,'}') !== false)? trim($arr,"'") : $arr;
                        }

                    return (is_array($return))? '{ '.PHP_EOL."\t".implode(",\t".PHP_EOL."\t",$return).PHP_EOL.' }' : $return;
                }

            public  function ChartOptions($opts)
                {
                    if(!is_array($opts))
                        return $this;

                    $this->options  =   "\t\tvar options =".$this->MakeJSObjects($opts).";";

                    return $this;
                }

            public  function ChartInstance()
                {
                    $str    =   (!empty($this->VarName))? "drawChart({$this->VarName},'{$this->id}');":"";
                    $str    .=  PHP_EOL;

                    return $str;
                }

            public  function CreateJavascript($settings = false)
                {
                    $library    =   (!empty($settings['lib']))? $settings['lib']:false;
                    $wrap       =   (!empty($settings['wrap']))? $settings['wrap']:false;
                    $wrap       =   (!empty($settings['data']) && is_array($settings['data']))? $settings['data']:array();

                    if($library)
                        $comp[] =   '<script type="text/javascript" src="https://www.google.com/jsapi?autoload={\'modules\':[{\'name\':\'visualization\',\'version\':\'1.1\',\'packages\':[\'corechart\']}]}"></script>'.PHP_EOL;

                    if($wrap)
                        $comp[] =   '<script type="text/javascript">'.PHP_EOL;

                    $comp[] =   '
google.load("visualization", "1", {packages:["corechart"]});
// Let the callback run a function
google.setOnLoadCallback(function() {';

                    for($i = 0; $i < count($settings['data']); $i++) {
                            $comp[] =   $settings['data'][$i].PHP_EOL;
                        }
                    $comp[] =   '
    });

// Give the function some arguments, first is data, second id
// You could do a third for the options attribute
function drawChart(ArrayElem,IdElem)
    {
        var data = google.visualization.arrayToDataTable(ArrayElem);'.PHP_EOL;
        if(!empty($this->options))
            $comp[] =   $this->options;

        $comp[] =   '

        var chart = new google.visualization.'.$this->chartType.'(document.getElementById(IdElem));

        chart.draw(data, options);
    }';

                    if($wrap)
                        $comp[] =   PHP_EOL.'</script>'.PHP_EOL;

                    return implode("",$comp);
                }
            public  function ChartKind($type = 'pie')
                {
                    switch($type) {
                            case('scatter'):
                                $this->chartType    =   'ScatterChart';
                                break;
                            default:
                                $this->chartType    =   'PieChart';
                        }

                    return $this;
                }
        }
?>

使用:

<html>
<head>
<?php
// Settings for the first chart
// This is so you can make multiple charts
$settings["incr"]           =   1;
// Id name for the chart (where to put the chart)
$settings["id"]             =   "piechart".$settings["incr"];
$settings["data"]["Task"]   =   "Lessons/Activity";

//**********************************//
// Your numbers from your db go here
//**********************************//
$settings["data"]['count(<50%)']            =   7;
$settings["data"]['count(Between 50-60%)']  =   3;
$settings["data"]['count(>60%)']            =   6;
//**********************************//
//**********************************//

// Create instance of GoogleCharts class
$Googlizer  =   new GoogleCharts();
// Create the pie chart
$Googlizer->CreatePie($settings);
// Save the instance of the js data array
$chart1_data    =   $Googlizer->ChartData();
// Save the instance of the js function
$chart1_inst    =   $Googlizer->ChartInstance();
// Write the whole shebangle to the page
echo $Googlizer ->ChartOptions(array("title"=>"My Weekly Plan","legend"=>"none"))
                ->ChartKind(GoogleCharts::PIE)
                ->CreateJavascript(array("data"=>array($chart1_data, $chart1_inst),"wrap"=>true,"lib"=>true));
?>
</head>
<body>
    <div id="piechart1" style="width: 900px; height: 500px;"></div>
</body>
</html>

给你:

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

google.load("visualization", "1", {packages:["corechart"]});
// Let the callback run a function
google.setOnLoadCallback(function() {
var DataSet1   =   [
                    ['Task', 'Lessons/Activity'],
                    ['count(<50%)', 7],
                    ['count(Between 50-60%)', 3],
                    ['count(>60%)', 6]
                ]


drawChart(DataSet1,'piechart1');


    });

// Give the function some arguments, first is data, second id
// You could do a third for the options attribute
function drawChart(ArrayElem,IdElem)
    {
        var data = google.visualization.arrayToDataTable(ArrayElem);
        var options = {
            title: 'My Weekly Plan',
            legend: 'none'
        };


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

        chart.draw(data, options);
    }
</script>
</head>
<body>
    <div id="piechart1" style="width: 900px; height: 500px;"></div>
</body>
</html>