2016-09-28 103 views
1

我需要藉助谷歌的折線圖與趨勢線,但我使用一個Ajax請求來獲取數據,把它裏面谷歌圖的繪製趨勢線

在AJAX文件,我插入一個數組圖形的和之後的元素我把它轉換的JSON這樣的:

$reply= json_encode($array); 
echo $reply; 

這是我的ajax答覆的內容:我喜歡填充該圖形

reply = [ 
    ["Periodo","Rome","Milan","Test"], 
    ["20160830",1,2,3], 
    ["20160831",2,3,6], 
    ["20160901",2,3,20], 
    ["20160902",20,30,12] 
    ]; 

在我的計劃:

var replyJSON = JSON.parse(reply); 
var data = google.visualization.arrayToDataTable(replyJSON); 

這是什麼,我也有類似的例子,我會做的,但在這裏我不能複製的Ajax調用:http://jsfiddle.net/roby492/srrrn9sa/384/

我需要得到答覆JSON,轉換的字符串日期在jquery日期以正確顯示趨勢線。

我該怎麼做?或者我怎樣才能通過Ajax發送日期而不是字符串的JSON?

謝謝。 羅伯特R.

回答

2

看看這個php to google chart via ajax example

在這裏推薦類似的設置

的示例構建JSON即由谷歌

可接受其允許DataTable的創建,從直接 JSON

以下是該答案的摘錄,即構建JSON

$rows = array(); 
$table = array(); 

$table['cols'] = array(
    array('label' => 'Time', 'type' => 'string'), 
    array('label' => 'Wind_Speed', 'type' => 'number'), 
    array('label' => 'Wind_Gust', 'type' => 'number') 
); 

while ($row = mysql_fetch_assoc($sqlResult)) { 
    $temp = array(); 
    $temp[] = array('v' => (string) $row['Time']); 
    $temp[] = array('v' => (float) $row['Wind_Speed']); 
    $temp[] = array('v' => (float) $row['Wind_Gust']); 
    $rows[] = array('c' => $temp); 
} 

$table['rows'] = $rows; 

echo json_encode($table); 

使用的JSON的實際日期列,變得有點棘手

主要是因爲在JavaScript月份的數字是從零開始的,不像PHP

所以如果格式化PHP中的日期,需要通過1

這對於一個漫長的格式聲明

通過在JSON的日期,以減少月數,你可以使用下面的格式,注意,它是作爲一個字符串傳遞...

"Date(2016, 8, 28, 15, 34, 40)" - >這相當於今天的日期
再次,月是從零開始的(8月=)

所以在此建一個日期在PHP格式,可以使用下面的...

$date1 = new DateTime(); 
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")"; 

產生上述

調整從對方的回答的片段,包括一個日期列中顯示的"Date(...)",看起來小號像這樣的...

$rows = array(); 
$table = array(); 

$table['cols'] = array(
    array('label' => 'Date', 'type' => 'date'), 
    array('label' => 'Wind_Speed', 'type' => 'number'), 
    array('label' => 'Wind_Gust', 'type' => 'number') 
); 

while ($row = mysql_fetch_assoc($sqlResult)) { 
    $date1 = $row['Date']; 
    $date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")"; 

    $temp = array(); 
    $temp[] = array('v' => (string) $date2); 
    $temp[] = array('v' => (float) $row['Wind_Speed']); 
    $temp[] = array('v' => (float) $row['Wind_Gust']); 
    $rows[] = array('c' => $temp); 
} 

$table['rows'] = $rows; 

echo json_encode($table); 

獲得通過從PHP AJAX上面的結果,你可以創建表格直接

var data = new google.visualization.DataTable(reply); 

無需解析JSON或使用arrayToDataTable

+0

這工作得很好,但我不得不解決這次的另一種方法是:在JSON中插入像這樣的日期「/ date(timestamp in ms)/」,並用一個函數來解析它,以便在日期對象中轉換字符串。 –

+0

感謝您的代碼示例! date_create()在我的情況下很有用:$ date1 = date_create($ row ['Date']) – AntonK

+0

@Roberto請使用投票按鈕旁邊的複選標記來標記此答案爲已接受?這將允許我將其他問題標記爲重複,並將它們發送到此處。 – WhiteHat