我有一个代码,可以生成一个多年的表格,每个表格分成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
答案 0 :(得分:1)
<?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>";
代码可以进行更多优化,但这可以完成工作。