以下代码将在每<tr></tr>
$product->title
<table>
<?php foreach ($products as $product) {
echo '<tr>
<td>'.$product->title.'</td>
</tr>';
}?>
</table>
但我想在每三列之后生成一行作为上述代码的输出。
<table>
<tr>
<td>$product->title/td>
<td>$product->title/td>
<td>$product->title</td>
</tr>
<td>$product->title</td>
<td>$product->title</td>
<td>$product->title</td>
</tr>
</table>
答案 0 :(得分:1)
我非常喜欢这种形式,它致力于输入内存。
<table>
<?php
$count = 0; // we gotta count them lines
foreach ($products as $product)
{
if ( ($count % 3) == 0 ) // every 3 lines
{
if ($count > 0) // not at first line
echo '</tr>'; // close previous row
echo '<tr>'; // open new row
}
++$count; // better count this one now.
echo '<td>'.$product->title.'</td>;
}
if ($count > 0)
echo '</tr>'; // close last row
?>
</table>
答案 1 :(得分:0)
$i=1;
<table>
<?php foreach ($products as $product) {
if ( $i<= 3 ) {
if($i==1) {
echo '<tr>';
}
echo '<td>'.$product->title.'</td>';
$i++;
}
else {
echo'</tr>';
$i=1;
}
}?>
</table>
答案 2 :(得分:0)
也许是这样的:
<table>
<?php
$count = count($products);
foreach ($products as $key => $product) {
// print on first row and third row
if($key % 3 == 0) {
echo '<tr>';
}
echo '<td>'.$product->title.'</td>';
// print on third row or on last element
if((($key + 1) % 3 == 0 && $key > 0) || $key == $count-1) {
echo '</tr>';
}
}
?>
</table>
如果数组未从0开始编制索引,则必须使用$key
变量的计数器。