代码给出了第一行的前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>
发布于 2015-06-01 12:13:17
最好的方法是@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
发布于 2015-06-01 12:08:17
这应该适用于你:
在这里,我首先使用range()
创建一个包含81个元素的数组。然后我将数组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
发布于 2015-06-01 12:10:40
您正在启动$i=0;
,因此第一个条件是true,它是在第一个结果之后放置</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
https://stackoverflow.com/questions/30573016
复制相似问题