2

我正在制作一个显示有 12 列的表格的循环。它以数字 1912 开始,以 2013 结束。问题是,当它循环到 1920 时,它没有余数并开始新的一行。我需要获取代码以在第 12 列之后创建新行。

这是我得到的结果:

http://imgur.com/AOIQf

这是我到目前为止所拥有的:

<?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>";
?>
4

3 回答 3

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>";

?>
于 2013-01-18T17:48:00.247 回答
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>";

解决方案 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>";
?>
于 2013-01-18T17:59:58.940 回答
0

您想每 12 列换行一次,只需跟踪当前列并使用它来确定何时应该结束该行(例如,每 12 列)-

$col = 1;

while ($Year <= 2013 && $col++) {
        if (!($col % $columns)) {
            //...

用于$Year确定何时包装只会使事情复杂化。

于 2013-01-18T17:50:11.073 回答