2012-07-15 53 views
-2

我使用OpenCart構建了一個遵循MVC結構設計的電子商務平臺。現在我正試圖在儀表板中顯示餅圖,爲此我使用的是Google Charts API。現在,當我只運行第一個數據顯示時,它不會獲取循環內的數據。這是我的代碼。我如何爲此設置一個循環?使用Google Charts API的餅圖不起作用

<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'], 
        $resultViewed = $this->model_report_product->getMostViewed(); 
        $stringResult ="var data= google.visualization.arrayToDataTable([ ['Product', 'Views'],"; 

        foreach($resultViewed as $resultKey => $resultValue) 
        { 
         //var_dump($resultValue); 
         $stringResult = $stringResult . "['".$resultValue['name']."',".$resultValue['quantity']."],"; 
         var_dump($stringResult); 
        } 
        $stringResult .= "]);"; 

        $this->data['Viewed'] = $stringResult; 
       ]); 

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

       var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
       chart.draw(data, options); 
      } 
     </script> 
    </head> 
    <body> 
     <div id="chart_div" style="width: 900px; height: 500px;"></div> 
    </body> 
</html> 

回答

1

您是否在PHP代碼中使用PHP標籤? 從你的代碼看來,你並不是。

無論如何,這種代碼應該正常工作對您:

<?php 
    $resultViewed = $this->model_report_product->getMostViewed(); 

    foreach($resultViewed as $resultValue){ 
     $results[] = "['".$resultValue['name']."', ".$resultValue['quantity']."]"; 
    } 
    $stringResult = implode(",", $results); 
?> 
<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'], 
        <?php 
        print $stringResult; 
        ?> 
       ]); 

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

       var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
       chart.draw(data, options); 
      } 
     </script> 
    </head> 
    <body> 
     <div id="chart_div" style="width: 900px; height: 500px;"></div> 
    </body> 
</html> 
+0

嗨, 也就是說錯誤在這裏。我使用了PHP標籤,但沒有發生。 – 2012-07-16 06:12:38

+0

請看我更新的答案。 – naf 2012-07-16 18:03:34