2011-04-15 62 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