我有一个PHP PDO查询,它从数据库中选择年份,月份和日期。它还计算,每一天都有的行数:如何正确地格式化PHP foreach循环?
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.
任何想法?
上述JSON数据创建数组highcharts的方式希望它和使用'json_encode()'将其发送到的JavaScript。 – jeroen
@jeroen你如何“建立”一个数组? – KoalatyCode
正如@jeroen所说,创建一个php数组(或特定的关联数组)并将其传递给echo json_encode。更多信息在这里:http://php.net/manual/en/function.json-encode.php – dylpickle