2013-07-08 36 views
2

我用下面的PHP代碼從陣列回波數據...拆分數組轉換成3列平等使用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個相等的列?

謝謝!

+2

此無關,使用PHP,以及一切與CSS – KyleK

回答

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>"; 
+0

打我衝! – AndrewPK

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> 
<? } ?> 
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>