简体   繁体   中英

display 5 arrays values per row

I am trying to make a calendar:

<table border="1">
       <tr><th colspan="7"><?php echo $current_month ?></th></tr>
        <tr>
         <?php foreach ($days as $day) {
            echo "<th>" . $day . "</th>";
         } ?>           
        </tr>
    <tr>
    <?php  
      foreach($keys as $row => $value) {
         echo "<td>" . $value . "</td>";
      }
    ?>
    </tr>
  </table>

How can I do to echo 7 values per row? AS you can see in the image, it displays all days in the same row. (of course, because I have put it in the same , but, how can I make that starts a new every 7 echo values?

Thank you!!! 在此处输入图片说明

You can use modulus to check if it has reached the seventh element and end the row.

<?php  
  foreach($keys as $row => $value) {
     if ($value % 7 == 0) {
        echo "<td>" . $value . "</td></tr><tr>";
     } else {
        echo "<td>" . $value . "</td>";
     }
  }
?>

An iteration counter is a pretty simple method.

<table border="1">
       <tr><th colspan="7"><?php echo $current_month ?></th></tr>
        <tr>
         <?php foreach ($days as $day) {
            echo "<th>" . $day . "</th>";
         } ?>           
        </tr>
    <tr>
    <?php
      $i = 0;   // Begin at 0 days written
      foreach($keys as $row => $value) {
          if ($i == 7){
             // Create new table row after every 7th iteration
             print "</tr><tr>";   // Add \n or \t for output formatting
             $i = 0;
          }             

          echo "<td>" . $value . "</td>";

          $i++;   // Increment $i each iteration
      }
    ?>
    </tr>
  </table>

Try the below code,

You can split the array into chunks of particular sizes, See more information about this from here array chunk

<?php
$current_month = 'Oct';
$days = array('1',2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
$chunk = array_chunk($days,7);
?>
<table border="1">
    <tr>
        <th colspan="7"> <?php
echo $current_month; ?>
        </th>
    </tr>
    <?php
foreach($chunk as $day) {
    echo '<tr>';
    foreach($day as $key) {
        echo "<th>" . $key . "</th>";
    }
    echo '</tr>';
} ?>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM