将foreach循环结果拆分为多列

时间:2015-01-28 12:30:41

标签: php html css

我目前在一个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>

1 个答案:

答案 0 :(得分:3)

<?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>';