php 如何在php循环中每行显示两个表格列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1793716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display two table columns per row in php loop
提问by brad
I would like to display data, two columns per row during my foreach. I would like my result to look like the following:
我想在 foreach 期间显示数据,每行两列。我希望我的结果如下所示:
<table>
<tr><td>VALUE1</td><td>VALUE2</td></tr>
<tr><td>VALUE3</td><td>VALUE4</td></tr>
<tr><td>VALUE5</td><td>VALUE6</td></tr>
</table>
Any help would be greatly appreciated.
任何帮助将不胜感激。
采纳答案by dusoft
$i=0;
foreach ($x as $key=>$value)
{
if (fmod($i,2)) echo '<tr>';
echo '<td>',$value,'</td>';
if (fmod($i,2)) echo '</tr>';
$i++;
}
this will output TR (row) each second time
这将每秒输出 TR(行)
ps: i haven't tested the code, so maybe you will need to add ! sign before fmod, if it doesn't output TR on first iteration, but on second iteration in the beginning...
ps:我还没有测试代码,所以也许你需要添加!在 fmod 之前签名,如果它在第一次迭代时没有输出 TR,而是在开始的第二次迭代中...
回答by Ben James
You can use array_chunk()to split an array of data into smaller arrays, in this case of length 2, for each row.
您可以使用array_chunk()将数据数组拆分为更小的数组,在这种情况下,每行的长度为 2。
<table>
<?php foreach (array_chunk($values, 2) as $row) { ?>
<tr>
<?php foreach ($row as $value) { ?>
<td><?php echo htmlentities($value); ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
Note that if you have an odd number of values, this will leave a final row with only one cell. If you want to add an empty cell if necessary, you could check the length of $rowwithin the outer foreach.
请注意,如果您有奇数个值,这将留下最后一行只有一个单元格。如果您想在必要时添加一个空单元格,您可以检查$row外部foreach.
回答by Md Imran Hossain
This would give you great table and for loop concept--
这将为您提供出色的表格和 for 循环概念--
<table border="1" cellspacing="0" cellpadding="2">
<?php
for($x=1; $x<=20; $x++)
{
echo "<tr>";
for($y=1; $y<=20; $y++)
{
echo "<td>";
echo $x*$y;
echo "</td>";
}
echo "</tr>";
}
?>
</table>
回答by Zaman-A-Piri Pasa
<table>
<?php
$i=0;
foreach ($x as $key=>$value)
{
if (!$i%2) echo '<tr>';
echo '<td>',$value,'</td>';
if ($i%2) echo '</tr>';
$i++;
}
?>
</table>

