我有一个数据表,其中包含 Material 、存储 Material 的数量以及收集日期(下面是数据示例):
|------------|--------------|-----------------|
| waste_type | total_weight | collection_date |
|------------|--------------|-----------------|
| Wood | 50 | 2014-05-24 |
| Wood | 75 | 2014-06-25 |
| Metal | 150 | 2014-06-25 |
| Plastic | 20 | 2014-07-10 |
|------------|--------------|-----------------|
使用以下查询:
$materialsCollected = $dm->createQuery('
SELECT SUM(efu.totalWeight) AS totalWeight, efu.wasteType, efu.collectionDate
FROM CoreBundle:EnviroFiguresUpload efu
GROUP BY efu.collectionDate
ORDER BY efu.collectionDate DESC'
);
$matColl = $materialsCollected->getResult();
然后 Symfony2 将其放入数组中,如下所示:
Array
(
[0] => Array
(
[totalWeight] => 50
[wasteType] => Wood
[collectionnDate] => 2014-05-24
)
[1] => Array
(
[totalCO2] => 75
[wasteType] => Wood
[collectionnDate] => 2014-05-24
)
[2] => Array
(
[totalCO2] => 150
[wasteType] => Metal
[collectionnDate] => 2014-05-24
)
[3] => Array
(
[totalCO2] => 20
[wasteType] => Plastic
[collectionnDate] => 2014-05-24
)
)
现在该数据被传递到 Flot.js 以显示堆叠条形图。我使用的示例代码是这样的:
<script>
init.push(function () {
// Visits Chart Data
var visitsChartData = [{
label: 'Visits',
data: [
[6, 1300], [7, 1600], [8, 1900], [9, 2100], [10, 2500], [11, 2200], [12, 2000], [13, 1950], [14, 1900], [15, 2000]
]
}, {
label: 'Returning Visits',
data: [
[6, 750], [7, 600], [8, 550], [9, 600], [10, 800], [11, 900], [12, 800], [13, 850], [14, 830], [15, 1000]
],
filledPoints: true // Fill points
}, {
label: 'New Visits',
data: [
[6, 300], [7, 450], [8, 250], [9, 100], [10, 400], [11, 300], [12, 200], [13, 850], [14, 830], [15, 1000]
],
filledPoints: true // Fill points
}];
// Init Chart
$('#jq-flot-bars').pixelPlot(visitsChartData, {
series: {
bars: {
show: true,
barWidth: .9,
align: 'center'
}
},
xaxis: { tickDecimals: 2 },
yaxis: { tickSize: 1000 }
}, {
height: 205,
tooltipText: "y + ' visitors at ' + x + '.00h'"
});
});
</script>
<!-- / Javascript -->
<div class="panel">
<div class="panel-heading">
<span class="panel-title">CO2 Savings</span>
</div>
<div class="panel-body">
<div class="graph-container">
<div id="jq-flot-bars" class="graph"></div>
</div>
</div>
</div>
我遇到的问题是我想将数据按月份分组,并在 Flot.js 中显示它们。但是,我不确定如何将它们正确分组。因此,每个条形图都会由每种 Material 组成,并且每个月都会有一个条形图。
如何按月对数据进行分组,然后将其传递到 Flot.js 图表?
最佳答案
您需要安装beberlei/DoctrineExtensions
bundle 并为学说启用MONTH
和YEAR
功能。看看我的回答here 。然后您可以轻松地按月对结果进行分组和过滤
SELECT SUM(efu.totalWeight) AS totalWeight, efu.wasteType, efu.collectionDate
FROM CoreBundle:EnviroFiguresUpload efu
GROUP BY MONTH(efu.collectionDate)
ORDER BY YEAR( efu.collectionDate ) DESC, efu.collectionDate DESC
<小时/>
另一个解决方案是在将结果传递给 Flot.js 之前在客户端上对结果进行分组(在 javascript 中)
关于php - 按月对数据进行分组,并使用 Symfony2、Twig 和 Flot.js 将其显示在多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898273/