2

我正在使用以下 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 个相等的列中?

谢谢!

4

3 回答 3

12

您可以使用 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>";
于 2013-07-08T20:26:58.497 回答
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>
于 2015-04-30T19:26:23.527 回答
1

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

<? $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>
<? } ?>
于 2014-12-17T12:26:09.303 回答