2016-09-28 141 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