我有一个PHP PDO查询,它从数据库中选择年,月和日。它还计算每天的行数:
SELECT
dateYear, dateMonth, dateDay,
count(dateDay) AS count_days
FROM just_ink
WHERE dateMonth = :month AND dateYear = :year AND deleted = 0
GROUP BY dateYear, dateMonth, dateDay
回应结果时:
foreach ($result as $subResult) {
foreach ($subResult as $row) {
$year = $row['dateYear'];
$month = $row['dateMonth'];
$day = $row['dateDay'];
$count = $row['count_days'];
echo $month . " " . $day . " " . $year . " " . $count . " lines, ";
}
}
返回如下值:
June 7 2016 3 lines, June 8 2016 1 lines,
这意味着,6月7日有3种形式,6月8日有1种形式。
现在进行格式化,我使用的是Highcharts基本折线图。数据需要以这种方式格式化:
<script>
$(function () {
$('#container').highcharts({
title: {
text: 'Monthly New Forms',
x: -20 //center
},
xAxis: {
title: {
text: 'Day of the Month'
},
categories: [
'1', '2', '3', '4', '5',
'6', '7', '8', '9', '10',
'11', '12', '13', '14', '15',
'16', '17', '18', '19', '20',
'21', '22', '23', '24', '25',
'26', '27', '28', '29', '30',
'31'
]
},
yAxis: {
title: {
text: 'Month of June'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Number of New Forms Per Day',
data: [1, 2, 3, 4, 5, 6]
}]
});
});
</script>
其中类别是x轴标题,而系列数据是每天的频率。所以,如果我想代表
June 7 2016 3 lines, June 8 2016 1 lines,
系列数据需要看起来像
0, 0, 0, 0, 0, 0, 3, 1, 0, etc.
有什么想法吗?
答案 0 :(得分:0)
首先创建一个包含每月每天元素的数组:
$counts = array_fill(1, 31, 0);
然后在你的循环中,填写当天的条目:
foreach ($subresult as $row) {
$day = $row['dateDay'];
$counts[$day] = $row['count_days'];
}
$counts = array_values($counts); // because json_encode treats it as an object if indexes don't start at 0
echo json_encode($counts);
我不确定您选择dateYear
和dateMonth
的原因,因为这些是查询的输入。你不需要在循环中设置这些变量,因为它们总是相同的。
答案 1 :(得分:0)
$highchartdata = []
foreach ($subResult as $row) {
$highchartdata[$row['dateDay']] = $row['count_days'];
}
echo json_encode($highchartdata);
从服务器获取上述json数据
obj = JSON.parse(data);// parse the json data
for (i = 1; i <=31; i++) {
if(!obj[i]) // if ith key is not defined make it 0
obj[i]=0;
}
console.log(obj);