在页面上创建多个 google.visualization 个图表

Create Multiple google.visualization Charts on a Page

我有一个使用 google 可视化代码生成的图表 看这里https://jsfiddle.net/eod8ysm1/

我想在电子邮件中的 table 中显示多个图表,因此我将所有 HTML 数据存储在一个对象 ($tempchartData) 中。

 $_SESSION["currentclient"] = $salesmengeotypes[1];
 $_SESSION["noanswer"] = "4";
 $_SESSION["declined"] = "5";
 $_SESSION["other"] = 4;

 ob_start();
 include "piecreator.php";
 $out1 = ob_get_clean();
 $tempchartData .= $out1;

但是,它似乎只适用于一张图表。有没有办法用多个图表来做到这一点?它调用的文件:

<?
$currentclient  =  $_SESSION["currentclient"];
$noanswer  =  $_SESSION["noanswer"];
$declined  =  $_SESSION["declined"];
$other  =  $_SESSION["other"];
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Signed Up', <? echo $currentclient;?>],
            ['No Answer',  <? echo $noanswer;?>],
            ['Declined',  <? echo $declined;?>],
            ['Other',  <? echo $other;?>]
        ]);

        var options = {
            title: 'Daily Sales Reports'
        };

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

        chart.draw(data, options);
    }
</script>
</head>
<body>
    <div id="piechart" 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() {
            // Chart data 1
            SetData1    =   [
                                ['Task', 'Hours per Day'],
                                ['Signed Up', 10 ],
                                ['No Answer',  20],
                                ['Declined',  40],
                                ['Other',  30]
                            ];

            // Chart data 2
            SetData2    =   [
                                ['Task', 'Hours per Day'],
                                ['Signed Up', 5 ],
                                ['No Answer',  10],
                                ['Declined',  35],
                                ['Other',  50]
                            ];
            // Pie Chart 1
            drawChart(SetData1,'piechart');
            // Pie Chart 2
            drawChart(SetData2,'piechart2');
        });

    // 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: 'Daily Sales Reports'
            };

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

            chart.draw(data, options);
        }


</script>
</head>
<body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
    <!-- create a drop for chart 2 -->
    <div id="piechart2" style="width: 900px; height: 500px;"></div>
</body>
</html>

jsFiddle 演示:

http://jsfiddle.net/vwnsbchh/1/

对于纯粹的 PHP 解决方案(如果您需要一些动态),您可以使用 class 从 php 变量中构建 javascript。 我发布的内容有效并按原样提供:

Update: This class (updated to include scatter/trend charts) is available for download (& scrutiny) at https://github.com/rasclatt/PHP-to-Google-PieCharts-Converter

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

            protected   $id;
            protected   $compiler;

            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}'";
                                    $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;
                }

            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"></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);
        var options = {
            title: \'Daily Sales Reports\'
        };

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

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

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

                    return implode("",$comp);
                }
        }
?>

使用:

<?php
// Create instance of GoogleCharts class
$Googlizer  =   new GoogleCharts();
?>
<html>
<head>
<?php
// Settings for the first chart
$settings["incr"]               =   1;
$settings["id"]                 =   "piechart".$settings["incr"];
$settings["data"]["Task"]       =   "Hours per Day";
$settings["data"]["Signed Up"]  =   10;
$settings["data"]["No Answer"]  =   20;
$settings["data"]["Declined"]   =   40;
$settings["data"]["Other"]      =   30;

// 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();

// Reset the settings
$settings                       =   array();

// Create chart 2
$settings["incr"]               =   2;
$settings["id"]                 =   "piechart".$settings["incr"];
$settings["data"]["Task"]       =   "Hours per Day";
$settings["data"]["Signed Up"]  =   5;
$settings["data"]["No Answer"]  =   15;
$settings["data"]["Declined"]   =   25;
$settings["data"]["Other"]      =   55;

// Same as chart 1
$Googlizer->CreatePie($settings);
$chart2_data    =   $Googlizer->ChartData();
$chart2_inst    =   $Googlizer->ChartInstance();

// Write the whole shebangle to the page
echo $Googlizer->CreateJavascript(array("data"=>array($chart1_data, $chart1_inst, $chart2_data, $chart2_inst),"wrap"=>true,"lib"=>true));
?>
</head>
<body>
    <div id="piechart1" style="width: 900px; height: 500px;"></div>
    <!-- create a drop for chart 2 -->
    <div id="piechart2" style="width: 900px; height: 500px;"></div>
</body>
</html>

class 将写入页面:

<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', 'Hours per Day'],
                    ['Signed Up', 10],
                    ['No Answer', 20],
                    ['Declined', 40],
                    ['Other', 30]
                ]


drawChart(DataSet1,'piechart1');

var DataSet2    =   [
                    ['Task', 'Hours per Day'],
                    ['Signed Up', 5],
                    ['No Answer', 15],
                    ['Declined', 25],
                    ['Other', 55]
                ]


drawChart(DataSet2,'piechart2');


    });

// 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: 'Daily Sales Reports'
        };

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

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