【发布时间】:2013-04-07 22:24:27
【问题描述】:
我正在使用 PHP 设置创建 Google 折线图的日期范围。对于范围内的每个日期,设置一个变量 ($running_balance) 以使用数据库中的数据在折线图上创建点。我希望能够设置变量 $end,它本质上动态地确定日期范围,但我不确定如何执行此操作,以便根据这个新范围重新绘制图表。我知道我可以创建一个包含 drawChart(); 的新函数来重绘图表,我将使用三个按钮将日期范围设置为 1 年、3 个月或 1 个月,但我不确定如何把这一切放在一起。这是我目前拥有的代码:
$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime('+365 days')));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt ) {
$date_display = $dt->format("D j M");
..... code to generate $running_balance .....
$temp = array();
$temp[] = array('v' => (string) $date_display);
$temp[] = array('v' => (string) $running_balance);
$temp[] = array('v' => (string) $running_balance);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
var table = <?php echo $jsonTable; ?>;
function drawChart() {
var data = new google.visualization.DataTable(table);
// Create our data table out of JSON data loaded from server.
// var data = new google.visualization.DataTable(<?=$jsonTable?>);
var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
formatter.format(data, 1);
var options = {
pointSize: 5,
legend: 'none',
hAxis: { showTextEvery:31 },
series: {0:{color:'2E838F',lineWidth:2}},
chartArea: {left:50,width:"95%",height:"80%"},
backgroundColor: '#F7FBFC',
height: 400
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
【问题讨论】:
-
你应该(至少)创建两个独立的函数。函数 #1 将检索数据。函数 #2 将调用数据检索函数并绘制图表。当您单击按钮/更改下拉菜单时,它应该调用一个处理函数,该函数将获取适当的数据并将其发送到图表绘制函数。基本上,取代码的前半部分(
drawChart()之前)并将其转换为接受 $end 参数的函数。您是否已经尝试过类似的方法?
标签: php javascript google-api google-visualization redraw