![](/img/trans.png)
[英]How do I query mysql databse to show data for each months in the previous years and current year?
[英]put data of each year in group of 5 years
我有一個代碼,可以生成一個年表,每個年表分為5年。如何將每年的每個數據放在其各自的列中?
這就是我到目前為止所得到的。
$chunkSize = 5;
$starting_year = 2006;
$ending_year = date("Y");
for($starting_year; $starting_year <= $ending_year; $starting_year++) {
$years[] = $starting_year;
}
for($i = 0; $i < count($years); $i+=5)
{
echo "<table class='table table-striped table-bordered'>";
echo '<thead><tr>';
echo '<th class="text-center">'.implode('<th class="text-center">', array_slice($years, $i, $chunkSize)).'</th>';
echo '</tr></thead>';
echo '<tr>';
$result= $myDB->query("SELECT total FROM ".$myDB->prefix("statistics")." WHERE year='$years[$i]'") or die(mysql_error());
$row = $myDB->fetchArray($result);
$total=$row['total'];
//echo "<td class='text-center'>".$total."</td>";
echo '<th class="text-center">'.implode('<th class="text-center">', array_slice($total, $i, $chunkSize)).'</th>';
echo '</tr>';
}
echo "</table>";
所需結果
2016 2017
total total
2011 2012 2013 2014 2015
total total total total total
2006 2007 2008 2009 2010
total total total total total
<?php
$chunkSize = 5;
$starting_year = 2006;
$ending_year = date("Y");
//create an array of years
$years = range($starting_year,$ending_year);
//[2006,2007,....,2016,2017]
//split years in required size
$chunked = array_chunk($years,$chunkSize);
//[ [2006,....,2010], [2011,...2015], [2016,2017]]
//reverse it
$reversed = array_reverse($chunked);
//[ [2016,2017], [2011,...2015], [2006,....,2010]]
echo "<table class='table table-striped table-bordered'><tbody>";
foreach($reversed as $reverse) {
echo "<tr>";
foreach($reverse as $year) {
echo "<th>{$year}</th>";
}
echo "</tr><tr>";
foreach($reverse as $year) {
$result= $myDB->query("SELECT total FROM ".$myDB->prefix("statistics")." WHERE year='{$year}'") or die(mysql_error());
echo "<td>{$result['total']}</td>";
}
echo "</tr>";
}
echo "</tbody></table>";
可以對代碼進行更多優化,但這可以完成工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.