看看这个php to google chart via ajax example
在这里推荐类似的设置
该示例构建了 google 可接受的 JSON
允许创建DataTable,直接从 JSON
以下是来自该答案的 sn-p,它构建 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(...)"
从另一个答案调整 sn-p 以包含日期列,可能看起来像这样......
$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);
通过ajax从php中得到以上结果,可以直接建表
var data = new google.visualization.DataTable(reply);
无需解析 JSON 或使用arrayToDataTable