无法正确打印 9x9 table

Can't print 9x9 table correctly

代码在第一行给出前 10 个数字,在其他 7 行给出 9 个数字,在最后一行给出 8 个数字。

如何获得 9x9 矩阵,以便所有行都有 9 个数字?

我什么都试过了,还是不行。有什么办法吗?

<table border=1>
    <tr>
    <?php

        for ($i = 1; $i < 82; $i++) {
            $arr[] = $i;
        }

        for ($i = 0; $i < 81; $i++) {
            echo '<td>' . $arr[$i] . '</td>';

        if ($i % 9 == 0 && $i != 0) {
            echo "</tr><tr>";
        }


        }

    ?>
    </tr>
</table>

这应该适合你:

这里我先创建一个81个元素的数组,range(). Then I array_chunk()将数组变成二维数组,其中每个子数组有9个元素

最后循环遍历所有子数组并将它们 implode() 合并为一行。

<table border=1>
<?php

    $arr = range(1, 81);
    $arr = array_chunk($arr, 9);

    foreach($arr as $v)
        echo "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";

?>
</table>

输出:

1   2   3   4   5   6   7   8   9
10  11  12  13  14  15  16  17  18
19  20  21  22  23  24  25  26  27
28  29  30  31  32  33  34  35  36
37  38  39  40  41  42  43  44  45
46  47  48  49  50  51  52  53  54
55  56  57  58  59  60  61  62  63
64  65  66  67  68  69  70  71  72
73  74  75  76  77  78  79  80  81

您正在启动 $i=0;,因此第一个条件为真,它被放置在 </tr> 第一个结果

之后
<table border=1>
    <tr>
    <?php
    for ($i = 1; $i < 82; $i++) {
    $arr[] = $i;
}
    $j=1;
    for ($i=0; $i<81; $i++)
    {
        echo '<td>'.$arr[$i].'</td>';

        if ($j%9==0) 
        {
           echo "</tr><tr>";
        }


    $j++;}
    ?>
    </tr>
</table>

输出

1   2   3   4   5   6   7   8   9
10  11  12  13  14  15  16  17  18
19  20  21  22  23  24  25  26  27
28  29  30  31  32  33  34  35  36
37  38  39  40  41  42  43  44  45
46  47  48  49  50  51  52  53  54
55  56  57  58  59  60  61  62  63
64  65  66  67  68  69  70  71  72
73  74  75  76  77  78  79  80  81

最好的是@Rizier所说的,但是如果你只想修改你的代码那么:-

<table border=1>
    <tr>
    <?php
    for ($i = 1; $i < 82; $i++) {
    $arr[] = $i;
}
    $j=1; //add a new count starts from 1
    for ($i=0; $i<81; $i++)
    {
        echo '<td>'.$arr[$i].'</td>';

        if ($j%9==0)  // check counter modules 9 will be zero or not. it will break after each 9 iteration.
        {
           echo "</tr><tr>";
        }


    $j++;} // increase the value of counter
    ?>
    </tr>
</table>

输出:-http://prntscr.com/7bu34m

试试这个

for ($i=1; $i<=81; $i++)
{
    echo '<td>'.$arr[$i].'</td>';

    if ($i%9==0 && $i!=1) 
    {
       echo "</tr><tr>";
    }


}

您的代码几乎是最新的...请回显 ''.$arr[$i].'';像这样在 if 条件下面的行...

<table border=1>
<tr>
<?php
for ($i = 1; $i < 82; $i++) {
    $arr[] = $i;
}
for ($i=0; $i<81; $i++)
{

    if ($i%9==0 && $i!=0) 
    {
       echo "</tr><tr>";
    }
    echo '<td>'.$arr[$i].'</td>';



}
?>
</tr>
</table>