只是一个看起来更好恕我直言的想法。
<?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
然后您可以使用该数据作为一个双 for-each 像这样:
$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>