How to display two table columns per row in php loop

前端 未结 4 1208
無奈伤痛
無奈伤痛 2020-12-03 08:36

I would like to display data, two columns per row during my foreach. I would like my result to look like the following:

 
V
相关标签:
4条回答
  • 2020-12-03 08:46
    <table>
    <?php
       $i=0;
       foreach ($x as $key=>$value)
       {
          if (!$i%2) echo '<tr>';
          echo '<td>',$value,'</td>';
          if ($i%2) echo '</tr>';
          $i++;
       }
    ?>
    </table>
    
    0 讨论(0)
  • 2020-12-03 08:54
    $i=0;
    foreach ($x as $key=>$value)
      {
      if (fmod($i,2)) echo '<tr>';
      echo '<td>',$value,'</td>';
      if (fmod($i,2)) echo '</tr>';
      $i++;
      }
    

    this will output TR (row) each second time

    ps: i haven't tested the code, so maybe you will need to add ! sign before fmod, if it doesn't output TR on first iteration, but on second iteration in the beginning...

    0 讨论(0)
  • 2020-12-03 09:06

    This would give you great table and for loop concept--

    <table border="1" cellspacing="0" cellpadding="2">
    
    <?php
    
         for($x=1; $x<=20; $x++)
            {
             echo "<tr>";
            for($y=1; $y<=20; $y++)
               {
              echo "<td>";
              echo $x*$y;
              echo "</td>"; 
               }
             echo "</tr>";
            }
    ?>
    </table>
    
    0 讨论(0)
  • 2020-12-03 09:10

    You can use array_chunk() to split an array of data into smaller arrays, in this case of length 2, for each row.

    <table>
    <?php foreach (array_chunk($values, 2) as $row) { ?>
        <tr>
        <?php foreach ($row as $value) { ?>
            <td><?php echo htmlentities($value); ?></td>
        <?php } ?>
        </tr>
    <?php } ?>
    </table>
    

    Note that if you have an odd number of values, this will leave a final row with only one cell. If you want to add an empty cell if necessary, you could check the length of $row within the outer foreach.

    0 讨论(0)
提交回复
热议问题