假设我有一个数组
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
现在在一个表行中显示一个数组值就像这样
echo "<table>";
foreach ($aSomeArray as $iSomeArrayKey => $iSomeArrayValue)
{
echo "<tr>";
echo "<td>".$iSomeArrayValue."</td>";
echo "</tr>";
}
echo "</table>";
但我想以表格格式显示值
1 2 3 4
5 6 7 8
9 10 11 12
我怎样才能做到这一点?
答案 0 :(得分:6)
编辑,这有效:
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
$i = 0;
echo "<table>\r\n";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
if (($i % 4) == 0) echo "\t<tr>\r\n";
echo "\t\t<td>" . $aSomeArrayValue . "</td>\r\n";
if (($i % 4) == 3) echo "\t</tr>\r\n";
$i++;
}
echo "</table>\r\n";
答案 1 :(得分:2)
只是一个看起来更好的恕我直言。
<?php
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
function createMatrix($width, $array)
{
$newArray = array();
$temp = array();
$count = 1;
foreach($array as $key => $value)
{
$temp[] = $value;
if(($count++ % $width) == 0)
{
$newArray[] = $temp;
$temp = array();
}
}
if( count($temp) > 0)
{
$newArray[] = $temp;
}
return $newArray;
}
将创建一个变量$width
的矩阵数组
然后,您可以将这些数据用作双重格式,如下所示:
$matrix = createMatrix(2, $aSomeArray );
foreach($matrix as $row)
{
echo "<tr>\n";
foreach($row as $td)
{
echo "\t<td>{$td}</td>\n";
}
echo "</tr>\n";
}
哪个产生:
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>11</td>
<td>12</td>
</tr>
答案 2 :(得分:1)
只是做一个跑步计数。因此,在foreach设置$i = 1
和每第四个结果之前,将计数重置为$i = 1
,然后结束行并重新打开一行。
答案 3 :(得分:1)
$aSomeArray = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13");
$columns = 4; // The number of columns to shown
echo "<table>";
$i = 0;
$trOpen = false; // just a flag if <tr> has been closed (paired with </tr>) or not.
foreach ($aSomeArray as $item) {
if ($i % $columns == 0) {
echo "<tr>";
$trOpen = true;
}
echo "<td>" . $item . "</td>";
if (($i + 1) % $columns == 0) {
echo "</tr>";
$trOpen = false;
}
$i++;
}
if ($trOpen) {
echo "</tr>"; // add '</tr>' if it is not yet added.
}
echo "</table>";
答案 4 :(得分:0)
echo "<table>";
echo "<tr>";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
echo "<td>".$aSomeArrayValue."</td>";
if($aSomeArrayValue % 4 == 0)
echo "</tr><tr>";
}
echo "</tr>";
echo "</table>";
答案 5 :(得分:0)
$i=1;
echo "<tr>";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
echo "<td>".$aSomeArrayValue."</td>";
$i++;
if($i%4==0){
echo "<tr></tr>";
}
}
echo "</tr>";
它也适用于4个元素不可分割。
答案 6 :(得分:0)
试试此代码
<?php
$i=0;
echo"<table>";
echo"<tr>";
foreach($aSomeArrayas as $val)
{
if($i %4 ==0)
{
echo"</tr><tr> <td> $val</td>";
}
else
{
echo"<td> $val </td>";
}
$i++;
}
echo"</tr>";
echo"</table>";
?>