$specs = array ('Name' => 'Cleopatra', 'Year' => '2008', 'Length' => '20ft', 'Make' => 'manufacturer', 'Model' => 'model', 'Engines Count' => '2', 'Fuel' => 'Diesel', 'Rudder' => 'rudder', 'Keel' => 'keel', 'Price' => '$1');
foreach ($specs as $label => $detail) {
echo "<tr>";
echo "<th>{$label}</th>";
echo "<td>{$detail}</td>";
echo "</tr>";
}foreach循环在每行中返回1列。如何呈现每行4列,如下所示
<tr>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
</tr>
<tr>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
<th>Label</th>
<td>Detail</td>
</tr>发布于 2011-12-15 04:19:57
只需添加计数器,就像这样:
echo "<tr>";
foreach ($specs as $label => $detail) {
if($i%4 == 0 && $i != 0) {
echo "</tr>";
echo "<tr>";
}
echo "<th>{$label}</th>";
echo "<td>{$detail}</td>";
$i++;
}
echo "</tr>";更新:固定边缘情况$i=0和<tr>的顺序正确
发布于 2011-12-15 04:30:18
设置一个计数器,每4次迭代打印一个新的<tr>。
$i = 0;
echo '<tr>';
foreach ($specs as $label => $detail) {
if($i !== 0 && $i%4 === 0){
echo '</tr><tr>';
}
echo "<th>{$label}</th>";
echo "<td>{$detail}</td>";
$i++;
}
echo '</tr>';发布于 2011-12-15 04:41:14
如果你记得学校的数学,你可以使用mod operator来得到除法运算的剩余部分。这就是你需要得到你想要的东西。
echo "<tr>";
foreach ($specs as $label => $detail)
{
$counter++;
//get remainder of division by 4, when 1 create new row
if ($counter % 4 == 1)
{
echo "</tr>";
echo "<tr>";
}
echo "<th>{$label}</th>";
echo "<td>{$detail}</td>";
}
echo "</tr>"; https://stackoverflow.com/questions/8511028
复制相似问题