将数组转储到表中
我有一个数组,我想将其转储到表中,但有一个新列 X 个项目。例如:
项目 1 |第 2 项 |第 3 项 |第 4 项 |
项目 5 |项目 6 |第 7 项 |第 8 项 |
第 9 项 |等等...
我已经可以使用以下代码在一定数量的项目(在本例中为 4)之后添加一个新列:
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$cols = 4;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($i=0; $i < count($input); $i++)
{
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
$n = $i+$c;
echo "<td>$input[$n]</td>";
}
echo "</tr>";
$i += $c;
}
echo "</table>";
但是由于某种原因,在一列以“四”结尾之后,下一列以“四”开头'六'。
I have an array which I would like to dump into a table, but have a new column X number of items. For example:
item 1 | item 2 | item 3 | item 4 |
item 5 | item 6 | item 7 | item 8 |
item 9 | and so on...
I can already make it add a new column after a certain number of items (in this case, 4) with this code:
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$cols = 4;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($i=0; $i < count($input); $i++)
{
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
$n = $i+$c;
echo "<td>$input[$n]</td>";
}
echo "</tr>";
$i += $c;
}
echo "</table>";
But for some reason, after one column ends with 'four', the next starts with 'six'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
数组函数可以非常神奇:
ref: http://php.net/manual/ en/function.array-chunk.php
Array functions can be quite magical:
ref: http://php.net/manual/en/function.array-chunk.php
在第一个循环中,$i 将增加 $c(始终为 3)。然后 for 循环会将 $i 值增加一 ($i++),这将使其跳过“五”。
您可以控制增量,也可以让 for 循环为您控制增量。
On your first loop $i will be incremented by $c (which will always be 3). Then the for loop will increase the $i value by one ($i++) which will make it skip the 'five'.
You either control the increment or let the for loop control it for you.
凯的回答是一个更好的解决方案。我所做的只是从
$i += $c
行中减去 1。Kai's answer is a much better solution. All I did was subtract 1 from the line
$i += $c
.您每隔 5 次就跳过一次,因为当您检测到需要执行新行时,您会使用 for 循环额外增加计数器一次。
这是另一种方法:
You're skipping every 5th because you are incrementing your counter an extra time with the for loop when you detect that you need to do a new row.
Here is another appraoch:
如果你清楚地理解,你想转储一个由你指定的行数的数组:
If understand you clearly, you want to dump an array in number of rows specified by you:
如果您想保留原来的逻辑,请将
$i
的增量更改为$i += (c$-1)
,因为您正在递增$除了列宽之外,i
也在循环中。然后还迎合空值。这将起作用:If you'd like to keep your original logic, change the increment of
$i
to$i += (c$-1)
since you are incrementing$i
in the loop in addition to your column width. Then also cater for empty values. This will work: