我正在创建一个显示包含12列的表的循环。它从数字1912开始,到2013年结束。问题是,当它循环到1920时,它没有余数并开始一个新行。我需要让代码在第12列之后创建一个新行。
这是我得到的结果:
这是我到目前为止所做的:
<?php
$columns = 12;
$Year = 1912;
echo "<table width="755" border="1">";
echo "<tr>";
while ($Year <= 2013) {
if (!($Year % $columns)) {
echo "</tr><tr>";
}
echo "<td>$Year</td>";
++$Year;
}
echo "</tr>";
echo "</table>";
?>
答案 0 :(得分:1)
<?php
$columns = 12;
$Year = 1912;
$i=1;
echo "<table width=\"755\" border=\"1\">";
echo "<tr>";
while ($Year <= 2013)
{
if ($i==13)
{
echo "</tr><tr>";
$i=1;
}
echo "<td>$Year</td>";
$Year++;
$i++;
}
echo "</tr>";
echo "</table>";
?>
答案 1 :(得分: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>";
你想用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>";
?>
答案 2 :(得分:0)
您想要包装每12列,只需跟踪当前列并使用它来确定何时应该结束行(例如,每隔12列) -
$col = 1;
while ($Year <= 2013 && $col++) {
if (!($col % $columns)) {
//...
使用$Year
确定何时换行只会使事情变得复杂。