将JSON传递给arrayToDataTable时遇到问题。我正在使用PHP While循环创建JSON ...
我正在尝试使用从DB动态更新的DataArray替换硬编码的JSON数据...
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['bar']}]}"></script>
while ($row = oci_fetch_array($query1, OCI_ASSOC+OCI_RETURN_NULLS)) {
$i++;
$total_obs += $row['CN'];
}
$dataArray = array($i,$total_obs);
json_encode($dataArray);
<script>
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Week', 'Totals'],
['1', 4],
['2', 5],
['3', 5],
['4', 8],
['5', 11],
['6', 13],
['7', 13],
['8', 14],
['9', 15],
['10', 0],
['11', 0],
['12', 0],
['13', 0],
['14', 0],
['15', 0],
['16', 0],
['17', 0],
['18', 0],
['19', 0],
['20', 0],
['21', 0],
['22', 0],
['23', 0],
['24', 0],
['25', 0],
['26', 0],
['27', 0],
['28', 0],
['29', 0],
['30', 0],
['31', 0],
['32', 0],
['33', 0],
['34', 0],
['35', 0],
['36', 0],
['37', 0],
['38', 0],
['39', 0],
['40', 0],
['41', 0],
['42', 0],
['43', 0],
['44', 0],
['45', 0],
['46', 0],
['47', 0],
['48', 0],
['49', 0],
['50', 0],
['51', 0],
['52', 0],
['53', 0]
]);
var options = {
chart: {
title: 'Totals in Fiscal Year 2016 - Cumulative Total',
subtitle: 'Oct 1, 2015 to Sep 30, 2016',
},
trendlines: {
0: {
type: 'linear',
color: 'green',
lineWidth: 3,
opacity: 0.3,
showR2: true,
visibleInLegend: true
}
},
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {format: 'decimal'},
height: 400,
colors: ['#d95f02'],
// trendlines: { 0: {} } // Draw a trendline for data series 0.
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
答案 0 :(得分:0)
Google可视化需要具有x,y值的连续2d数组。假设$row['CN']
保存值,您应该像这样构造PHP数组:
$total_obs = array();
$total_obs[] = array('Week', 'Totals');
$i=0;
while ($row = oci_fetch_array($query1, OCI_ASSOC+OCI_RETURN_NULLS)) {
$i++;
$total_obs[] = array($i, $row['CN']);
}
然后在<script>
中回复它:
var data = google.visualization.arrayToDataTable(<? echo json_encode($total_obs); ?>);
这将导致(示例):
var data = google.visualization.arrayToDataTable([["Week","Totals"],[1,4],[2,5],..]);
这正是你和谷歌可视化所想要的......:)
在while
循环后执行此操作后,如果所有星期都不存在,请将阵列更新为52周:
for ($i=count($total_obs);$i<53;$i++) {
$total_obs[] = array($i, 0);
}