将foreach循环结果拆分为多列

将foreach循环结果拆分为多列

我目前正在将我所有的兴趣都列在一个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>';

关于php - 将foreach循环结果拆分为多列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28192329/

10-11 08:37