将 foreach 循环结果拆分到多个列上


Split foreach loop results over multiple columns

我目前在一个div中列出了我所有的兴趣。但是,我想将这些分散到各个列中。所以每列有 4 个兴趣。如何更改我的 CSS 以允许此操作?

          <?php
          $interests = get_terms('interests',array( 'taxonomy' => 'interests' )); 
          foreach($interests as $term){
              echo '<li>'.$term->name.'</li>';
          }
          ?>

首选的 HTML 输出:

            <div class="columns">
                <ul>
                    <li>F1</li>
                    <li>Cycling</li>
                    <li>Football</li>
                    <li>Rugby</li>
                </ul>
            </div>
            <div class="columns">
                <ul>
                    <li>Running</li>
                    <li>Swimming</li>
                </ul>
            </div>
<?php
      $interests = get_terms('interests',array( 'taxonomy' => 'interests' )); 
      echo '<div class="columns">';
      $index = 0;
      foreach($interests as $term){
          if ($index > 0 and $index % 4 == 0) {
              //if not the first row and dividable by 4
              echo '</div><div class="columns">';
          }
          echo '<li>'.$term->name.'</li>';
          $index++;
      }
      echo '</div>';
  ?>

对于您的评论:

$interests = get_terms('interests',array( 'taxonomy' => 'interests' )); 
$count = count($interests);
$numItemsPerRow = ceil($count / 3);
//we need this in case of 2-1-1 for example, otherwise you get 2-2
$numItemsOffsetFix = $count % 3 == 1;
$index  = 0;
echo '<div class="columns">';
foreach($interests as $term){
    if ($index > 0 and $index % $numItemsPerRow == 0) {
        echo '</div><div class="columns">';
        if ($numItemsOffsetFix) {
            $numItemsPerRow--;
            $numItemsOffsetFix = false;
        }
    }
    echo '<li>'.$term->name.'</li>';
    $index++;
}
echo '</div>';