使用PHP将数组拆分为3个相等列

时间:2013-07-08 20:22:53

标签: php foreach

我正在使用以下PHP代码来回显数组中的数据......

foreach($businessnames as $b)
{
    $theurl = get_term_link($b, 'businessnames');
    echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
}

我使用它来将数据分成3个相等的列,但现在我需要按照数组的顺序执行3个相等的列(而不是像CSS浮动原因那样从“从左到右”)。我想我需要用PHP计算数组中的总值然后除以它,但我不确定代码是什么。我一直在四处寻找,但没有找到能够解决这个问题的事情。

我如何调整我的代码以将数组的数据放入3个相等的列?

谢谢!

3 个答案:

答案 0 :(得分:10)

您可以使用array_chunk将数组拆分为

$cols = array_chunk($businessnames, ceil(count($businessnames)/3)); 

foreach ($cols as $businessnames){
    echo "<ol class='col'>";
    foreach($businessnames as $b)
    {
        $theurl = get_term_link($b, 'businessnames');
        echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
    }
    echo "</ol>";
}

或者,您可以使用纯css解决方案。

echo "<ol style='column-count:3; -o-column-count:3; -moz-column-count:3; -webkit-column-count:3;'>";
foreach($businessnames as $b)
{
    $theurl = get_term_link($b, 'businessnames');
    echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
}
echo "</ol>";

答案 1 :(得分:3)

这是一种更简单的方法:

<?php $items_per_col = ceil(count( $posts ) / 3); // 3 is columns count ?>

<div class="row">
   <div class="col-sm-4"> <!-- col-sm-4 for 3 columns -->
      <?php foreach ( $posts as $i => $post ): ?>

         <?php if($i % $items_per_col === 0 && $i !== 0): ?>
            </div><div class="col-sm-4"> <!-- col-sm-4 for 3 columns -->
         <?php endif; ?>

         <?php echo $post; ?>

      <?php endforeach; ?>
   </div>
</div>

答案 2 :(得分:0)

以下是我如何制作您需要的任何数量的列。

<? $columns = array(); //prepare array for our columns
$i = 0; //prepare counter
foreach ($posts as $value) {

    // reset the counter when we reach the third column (column 0, column 1, column 3 -> reset -> column 0)
    //change the $i == 3 to $i == 4 if you need 4 columns of whatever amount of columns you need
    if($i == 3){ $i = 0; }

    //this is just for php warning "array_push() expects parameter 1 to be array, null given"
    //if the sub array doesn't exist, make one
    if(!isset($columns[$i])){
        $columns[$i] = array();
    }

    //add the chunk to the column array
    array_push($columns[$i], $value);
    $i++;

} ?>

<? foreach ($columns as $key => $column) { ?>

    <div class="triple-column column<? echo $key //columns are numbered, it's usefull for CSS ?>">
        <? foreach ($column as $post) {

        // Do something with the $post here
        // $post is the single element from the array we had at the beginning

        } ?>
    </div>
<? } ?>