【问题标题】:php foreach loop helpphp foreach 循环帮助
【发布时间】:2011-04-15 13:57:55
【问题描述】:

我有一个 foreach 循环,它为我构建了一个产品页面,基本上它把我的产品放在 3 行中。

查看代码:

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 的数组中的图像路径,看起来与此类似,

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

我怎样才能做到这一点?我已经四处乱跑了几个小时了:(

【问题讨论】:

  • 所以你总是每行有三个项目?但是要在结果中随机添加图片(第一行除外)?
  • 是的,你完美地总结了我想要的东西!
  • 可能没有什么关系,但你上面的示例数组,只有第一项被正确引用。

标签: php codeigniter loops foreach


【解决方案1】:

对不起,我没有太多时间给你写完整的代码,但以下应该可以工作:

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

【讨论】:

    【解决方案2】:

    所以我要做的是为您的图像创建一个哈希表,以及您希望在表中的哪些点显示它们。表的键是索引,值是图像名称。

    假设$currentItem 是从零开始的,那么对于第一行中的第三项,您拥有的第一个键将是2

    然后在你的循环中,检查$currentItem 是否在哈希表中。如果是,打印图像并增加$currentItem(并重新计算行和列),然后打印$product。如果它不在哈希表中,则像平常一样打印$product

    【讨论】:

    • 你能给我一个哈希表的例子吗,我以前从未听说过这个词,或者甚至是循环的例子?即使是伪代码
    • @sea_1987 hashtable == 关联数组
    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多