解决方案 1
您需要为匹配的年份附加和前置列,如下所示:
这是这样做的代码:
<?php
$columns = 12;
$startingYear = 1912;
$endingYear = 2013;
$realStartingYear = $startingYear;
$realEndingYear = $endingYear;
//Find the real starting year by going back a year until we hit the right one
while ($realStartingYear % $columns) {
$realStartingYear--;
}
//Find the real ending year by going forward a year until we hit the right one
while ($realEndingYear % $columns) {
$realEndingYear++;
}
echo '<table width="755" border="1">';
echo "<tr>";
for ($year = $realStartingYear; $year < $realEndingYear; $year++) {
if (!($year % $columns)) {
echo "</tr><tr>";
}
echo "<td>" . ($year >= $startingYear && $year <= $endingYear ? $year : "") . "</td>";
}
echo "</tr>";
echo "</table>";
?>
如果您还想显示其他列,只需更改
echo "<td>" . ($year >= $startingYear && $year <= $endingYear ? $year : "") . "</td>";
至
echo "<td>" . $year . "</td>";
解决方案 2
您想以 1912 开始表格,如下所示:
代码会简单很多:
<?php
$columns = 12;
$startingYear = 1912;
$endingYear = 2013;
echo '<table width="755" border="1">';
for ($i = $startingYear; $i <= $endingYear; $i += $columns) {
echo "<tr>";
for ($j = 0; $j < $columns; $j++) {
echo "<td>" . ($i + $j) . "</td>";
}
echo "</tr>";
}
echo "</tr>";
echo "</table>";
?>