看看这个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
这工作得很好,但我不得不解决这次的另一种方法是:在JSON中插入像这样的日期“/ date(timestamp in ms)/”,并用一个函数来解析它,以便在日期对象中转换字符串。 –
感谢您的代码示例! date_create()在我的情况下很有用:$ date1 = date_create($ row ['Date']) – AntonK
@Roberto请使用投票按钮旁边的复选标记来标记此答案为已接受?这将允许我将其他问题标记为重复,并将它们发送到此处。 – WhiteHat