2015-09-24 43 views
1

我有一個約90個項目的PHP對象。我試圖用交替列輸出這些行。我當前的代碼是輸出2項每行是:如何替換每行的列數?

<?php 
    $_collectionSize = $_productCollection->count(); 
    $_columnCount = 2; 
    $i = 0; 
?> 

<?php foreach ($_productCollection as $_product): ?> 

    <?php if ($i++ % $_columnCount == 0): ?> 
     <section class="row"> 
    <?php endif ?> 

      <div class="six columns"></div> 

    <?php if ($i % $_columnCount == 0 || $i == $_collectionSize): ?> 
     </section> 
    <?php endif ?> 

<?php endforeach; ?> 

我怎麼能修改此代碼以交替的列數的每一行,使輸出會像:

<div class="row"> 
    <div class="six columns"></div> 
    <div class="six columns"></div> 
</div> 

<div class="row"> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
</div> 

<div class="row"> 
    <div class="six columns"></div> 
    <div class="six columns"></div> 
</div> 

<div class="row"> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
    <div class="three columns"></div> 
</div> 

感謝

+0

谷歌的PHP模板引擎(諸如Smarty或嫩枝)。您可以稍後感謝我:) –

回答

1

我想塊我在塊陣列由兩個,然後按住下一個需要重點用於輸出不同的標記:

$items = array(
    'Product 1', 
    'Product 2', 
    'Product 3', 
    'Product 4', 
    'Product 5', 
    'Product 6', 
    'Product 7', 
    'Product 8', 
    'Product 9', 
    'Product 10', 
    'Product 11', 
    'Product 12',  
); 

$chunked = array_chunk($items, 2); 

// variable to hold next <div class="six columns"></div> markup 
$needle = 0; 

foreach ($chunked as $key => $items) { 

    if ($key == $needle) { 
     if ($key !== 0) echo "</div>\n"; 
     echo "<div class=\"row\">\n"; 
     foreach($items as $item) { 
      echo "<div class=\"six columns\">{$item}</div>\n"; 
     } 
     echo "</div>\n<div class=\"row\">\n"; 
     // skip two array items 
     $needle = $needle + 3; 
    } else { 
     foreach($items as $item) { 
      echo "<div class=\"three columns\">{$item}</div>\n"; 
     } 
    } 
} 
echo "</div>"; 

Working demo

0

你的意思是這樣的,使用模2? :

<?php foreach ($_productCollection as $_product): ?> 

    <?php if ($i++ % $_columnCount == 0): ?> 
     <section class="row"> 
    <?php endif ?> 

    <?php if ($i % 2 == 0): ?> 
      <div class="six columns"></div> 
      <div class="six columns"></div> 
    <?php else ?> 
      <div class="three columns"></div> 
      <div class="three columns"></div> 
      <div class="three columns"></div> 
      <div class="three columns"></div> 
    <?php endif ?> 

    <?php if ($i % $_columnCount == 0 || $i == $_collectionSize): ?> 
     </section> 
    <?php endif ?> 

<?php endforeach; ?> 
+0

感謝您的回覆,但這不是我想要的。每行輸出3,3,3,6,6.我需要一排6,6,然後3,3,3,3交替 – Robert