今天找了一天的jquery图表插件,弄了一整天的Highcharts,记下来以备下次用到,我用的比较简单的,显示年份内的每个月的用户注册量,数据表详细就不用了,SQL执行后的效果是:
后台operate.php文件内容是这样:
if ($Gaction == 'getchart'){ //这等同于$_GET['action'] == 'getchart'
$query = $db->result_array("select DATE_FORMAT(from_unixtime(finishtime),'%Y') as years, DATE_FORMAT(from_unixtime(finishtime),'%c') as months,count(rid) as count from 2x3_servrecord where DATE_FORMAT(from_unixtime(finishtime),'%Y') = '2012' group by months "); //这是用到自定义的一个mysql类
$count = array('0','0','0','0','0','0','0','0','0','0','0','0'); //这是先自定义的12个月的数组
if ($query){
foreach ($query as $row){
$count[$row['months']] = $row['count'];
}
}
echo json_encode($count);
}
前台展示要加载的两个JR文件就不列出来了,图表的JS是:
<script type="text/javascript">
<!--
$(function () {
var chart;
var options;
$(document).ready(function() {
var count;
options = {
chart: {
renderTo: 'container1',
type: 'column'
},
title: {
text: '深圳二乘三科技技术有限公司'
},
subtitle: {
text: '统计图'
},
xAxis: {
categories: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
},
yAxis: {
min: 0,
title: {
text: '次数'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' 次';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: []
};
$.getJSON('index.php?m=2x3&a=operate',{
'action':'getchart'
},function(data){
var series = { // <-------------------- create just one series object
type: 'column',
name: '2012',
data: [] //data array for new series
};
var i=0;
for(i=0;i<=11;i++){
var j =parseInt(data[i]); //这个很重要,TNN的,弄了我好几小时才发现
series.data.push(j);
}
options.series.push(series); // <-------- pushing series object
var chart = new Highcharts.Chart(options);
});
});
});
//-->
</script>
图表的HTML显示是:
<div id="container1" style="min-width: 400px; height: 400px;margin:0 auto"></div>
这个例子上就有了。
最后显示效果图:
数据有点少哈~
这个最难弄的就是从数据库中取出数据后怎么放入series: []里了,这个只是简易的2012的柱图,其它的可以触类旁通吧~
参考地址:http://stackoverflow.com/questions/7810098/php-json-highcharts-load-database-result
ps:$count[$row['months']] = $row['count'];应改为$count[$row['months']-1] = $row['count'];不然就跳了一个月,2月数据跑到3月份显示去了~