2016-01-06 68 views
0

我正在使用Google圖表創建線圖。然而在JavaScript部分,我試着通過我的PHP變量到數組但是我得到其內容的錯誤消息:給定Google圖表不接受PHP變量

沒有足夠的列繪製圖表要求。

我的代碼:

<!-- Google Charts --> 
<div id="chart_line_graph" style="width: 100%; height: 400px; margin: 0 auto;"></div> 

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 

<? 
    $titleArray = array(
         'Week' 
         ); 
     $count = 0; 
     //Get all headers 
     $query = 'SELECT `keyword` FROM `'.$tableName.'` ORDER BY `keyword`'; 
     $results = mysqli_query($conn, $query); 
     while($row = mysqli_fetch_assoc($results)){ 
      if($count < 5) //Get first 5 keywords 
       $titleArray[] = $row['keyword']; 
      $count++; 
     } 

     $data = array(); 
     $data[] = json_encode($titleArray); 

     foreach($columns as $column){ 
      $weekData = array(); 
      $weekData[] = "'".$column."'"; 
      $query = 'SELECT `'.$column.'` FROM `'.$tableName.'` ORDER BY `keyword`'; 
      $results = mysqli_query($conn, $query); 
      $count = 0; 
      while($row = mysqli_fetch_assoc($results)){ 
       if($count < 5) 
        $weekData[] = (Integer)$row[$column]; 
       $count++; 
      } 
      $data[] = json_encode($weekData); 
     } 

?> 

<script> 
    google.charts.load('current', {'packages':['corechart']}); 
    google.charts.setOnLoadCallback(drawChart); 

    function drawChart() { 
    var data = google.visualization.arrayToDataTable([ 
    <?php 
     foreach($data as $weekData){ 
      echo $weekData.','; 
     } 
     ?>  

    ],false); 

    var options = { 
     title: '<?echo ucwords($_SESSION['clientName']);?> Keywords', 
     curveType: 'function', 
     legend: { position: 'right' } 
    }; 

    var chart = new google.visualization.LineChart(document.getElementById('chart_line_graph')); 

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

我每次運行它,我得到了同樣的錯誤消息。我試着輸出結果並直接複製並粘貼到JavaScript中,並創建了圖形。

任何想法爲什麼這不起作用?

編輯:

數據:

["Week","aker aberdeen","alma tavern","ancillary items","baby change sign","baby change units"], 
["10_12_2015",36,11,37,30,48], 
["17_12_2015",36,10,35,27,43], 
["24_12_2015",26,11,35,26,44], 
["31_12_2015",29,11,32,23,42], 
+0

你會告訴我們什麼樣的數據看起來像餵給'google.visualization.arrayToDataTable' – WhiteHat

+0

我不能評論PHP方面,因爲我在那方面不強,但要確保數據是瀏覽器正在接收的代碼實際上出現了什麼。你的數組結構看起來不錯。雖然你得到的錯誤表明它沒有得到你的數組。或陣列的格式不正確(像有它周圍的東西或一些報價)。 – nbering

+0

當我看到它缺少對數組號的信號,我不知道爲什麼它不撿起來 – MrHappySandwich

回答

0

我想通了。出於某種原因,mysqli無法正常工作。我將其從程序化方式改爲面向對象的方式,一切都奏效了。我不知道爲什麼我只知道它的工作。