当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Count array items and add div after certain number

问题描述:

$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>";

}

The foreach loop returns 1 column in each row. How can I render 4 columns per row like so

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

网友答案:

Just add counter, something like this:

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>";

Update: Fixed edge case $i=0 and <tr>'s in right order

网友答案:

Set a counter, and every 4th iteration, print a new <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>';
网友答案:

If you remember your maths from school, you can use the mod operator to get the remainder of a division operation. This is what you need to get what you want.

 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>"; 
网友答案:

This carries the assumption that your index is zero based.

First we define the number of columns we want in each row. Then, we define two rules sets: when to start a new row and when to end a row.

We want to start a new row on the first iteration and anytime the current iteration count is divisible by the number of columns we want in each row.

We want to end a row when we are on the last iteration. Also we will end a row anytime that we are not on the first iteration and the total count of the collection minus the current iteration count is divisible by the number of columns we want in each row minus one.

$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>';
    }
}

This method allows you to only write the opening and closing tags once so that editors don't think that you are forgetting to open or close something.

分享给朋友:
您可能感兴趣的文章:
随机阅读: