Google图表无法循环打印

时间:2015-12-22 13:34:14

标签: javascript php google-visualization pygooglechart

我要循环显示Google图表。没有循环我的图表工作正常,但当我尝试在循环中添加它我得到它只为第一次迭代,我如何解决它,请查看此

<script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart() {

            var data = google.visualization.arrayToDataTable([
              ['Task', 'Daily Report'],
              ['Points Achieved',     <?php echo $points_achieved?>],
              ['Points Left',         <?php echo $points_left?>]
            ]);

            var options = {
             backgroundColor: 'transparent',
              title: '' ,
              chartArea:{right:0,top:0,width:"90%",height:"100%" }        
              ,height: 150
              ,width: 200,
             };

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

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


<?php
     $sql= "SELECT * FROM employees";
     $query= mysqli_query($connection, $sql);
    while($res= mysqli_fetch_assoc($query)): ?>

<div id='piechart'></div>
//other data from database comes here 

<?php endwhile;?>

1 个答案:

答案 0 :(得分:1)

由于您正在绘制多个图表,我建议修改drawChart函数以接受图表ID和数据作为参数:

function drawChart(chartId,data) {
    var dataTable = google.visualization.arrayToDataTable(data);
    var options = {
         backgroundColor: 'transparent',
         title: '' ,
         chartArea:{right:0,top:0,width:"90%",height:"100%" },
         height: 150
        ,width: 200,
    };
    var chart = new google.visualization.PieChart(document.getElementById(chartId));
    chart.draw(dataTable, options);
}

然后你可以迭代PHP数组并调用drawChart函数:

<?php
foreach ($reports as $key => $report) {
    $chartId = "piechart_$key";
    //prepare chart data
    $chartData = array(
        array("Task", "Daily Report"),
        array("Points Achieved" , $report["Points Achieved"]),
        array("Points Left" , $report["Points Left"])
    ); 


?>
  <div id='<?php echo $chartId; ?>'></div> 
  <script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>

假设$reports数组具有以下结构:

//input data example ( replace it with data retrieved from DB)
$reports = array(
    "R1" => array("Points Achieved" => 20, "Points Left" => 4),
    "R2" => array("Points Achieved" => 40, "Points Left" => 14),
    "R3" => array("Points Achieved" => 10, "Points Left" => 0)
);

Working example