2011-12-14 28 views
0
$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列,像这样计数数组项并在特定数字后添加div

<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> 
+3

每列4行?或每列的列?你的例子是每行的列。 – Jon 2011-12-14 20:15:22

+0

编辑。感谢您的注意 – CyberJunkie 2011-12-14 20:17:22

回答

5

只需添加计数器,像这样:

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>的向右顺序

1

套装一个计数器,并且每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>'; 
1

如果你从学校还记得你的数学,你可以使用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>"; 
1

这承载了您的索引是基于零的假设。

首先我们定义每行所需的列数。然后,我们定义两个规则集:何时开始新行和何时结束行。

我们希望在第一次迭代时开始一个新行,并且任何时候当前迭代计数都可以被我们在每一行中需要的列数整除。

我们想在最后一次迭代时结束一行。当我们不在第一次迭代时,我们也会结束一行,并且集合的总数减去当前的迭代次数可以被我们希望在每一行中减去一列的列数整除。

$cols_in_row = 5; 
foreach ($array as $i => $item) 
{ 
    if ($i == 0 || $i % $cols_in_row == 0) 
    { 
     echo '<tr>'; 
    } 

    echo '<td>'.$item.'</td>'; 

    if ($i + 1 == count($array) || ($i != 0 && count($array) - $i % ($cols_in_row - 1))) 
    { 
     echo '</tr>'; 
    } 
} 

此方法允许您只写一次开启和关闭标签,以便编辑者不会认为您忘记打开或关闭某些东西。