2011-04-15 63 views
0

我有一個foreach循環建立我的產品頁面基本上它把我的產品在3PHP的foreach循環的幫助

行看到代碼:

foreach ($product_sets as $product) 
{ 
    $currentRow = ceil($currentItem/3); 
    $currentColumn = $currentItem - (($currentRow - 1) * 3); 
    if ($number_of_blanks == 2) : 
     if (($number_of_rows > 1 && $currentRow == ($number_of_rows - 1) && $currentColumn == 2) || ($number_of_rows == 1 && $currentColumn == 1)) : 
    ?> 
      <li><img src="<?php echo site_url('assets/img/blocks/guarantee.png'); ?>" alt="5 Year Guarantee" width="242" height="156"></li> 
    <?php 
      $currentItem++; 
     endif; 
    endif; 
    ?> 
    <li class="<?php if($currentItem % 3 == 0) echo 'endHomeBlock';?>"> 
     <?php $this->load->view('blocks/product_small', array('product' => $product)); ?> 
    </li> 
    <?php 
     $currentItem++; 

    } 

什麼,我想能要做的是在第一行的末尾放置一個圖像(一個銷售點),然後在其他行中隨機放置一個圖像(銷售點),但在一行中保留3個項目(包括圖像銷售點)。我有一個名爲圖像陣列的圖像路徑,看起來類似於此,

$images = array(
    'iamge1.png', 
    'image2.png, 
    'image3.png, 
    'image4.png, 
); 

我該如何實現這一目標?我一直在爲幾個小時左右(

+1

那麼你將永遠有每行3個項目?但隨機想要在結果中添加圖像(除了第一行以外,是隨機的)? – zsalzbank 2011-04-15 14:01:22

+0

是的,你summised我想要的完美! – 2011-04-15 14:08:51

+0

也許沒什麼關係,但是你上面的例子數組,只有第一項被正確引用。 – Christian 2011-04-15 14:14:25

回答

0

對不起,我沒有寫在你的全部代碼太多的時間,但下面應該工作:

<ul> 
    <li><?php 
     foreach($items as $i=>$item){ 
      // ...write item... 
      if(($i % 3)==0 && $i!=0){ // if multiple of 3 and not the first time.. 
       ?></li><li><?php 
      } 
     } 
    ?></li> 
</ul> 
0

所以我會做的是創建一個你的圖像的哈希表,並在表中的哪些點你想顯示它們。表的關鍵是索引和值將是圖像的名稱。

假設$currentItem是從零開始,你將有第一個關鍵是2第一行中的第三項。

然後在循環,檢查,看看如果$currentItem位於散列表中,則打印圖像並增加$currentItem(並重新計算行和列),然後打印$product。 f它不在哈希表中,只是像正常一樣打印$product

+0

可否給我一個哈希表的例子,我從來沒有聽說過這個術語,或者甚至是循環的例子?即使它僞代碼 – 2011-04-15 14:16:01

+0

@ sea_1987哈希表==關聯數組 – 2011-04-15 14:21:07