foreach由于某种原因无法正常工作

时间:2018-08-12 13:51:56

标签: php foreach

我的脚本的这一部分显示了给出我网站的最新报价,但由于某种原因,它显示的报价是图片显示的3倍。

Image Here

这是脚本随附的代码

<?php foreach($specialoffers as $offer) if ($tmp++ < 3) { ?>
<div class="col-md-4">
    <div class="col-md-12">
        <?php if($specialoffers[0]->price > 0){ ?> <span class="wow bounce ttu"><?php echo trans('0536');?> <b><?php echo trans('0388');?></b> <small><?php echo $specialoffers[0]->currCode;?></small> <?php echo $specialoffers[0]->currSymbol; ?><?php echo $specialoffers[0]->price;?></span>
        <?php } ?>
        <div class="imgLodBg">
        <div class="load"></div>
        <a href="<?php echo base_url(); ?>offers">
        <img data-wow-duration="0.2s" data-wow-delay="1s" class="wow fadeIn" src="<?php echo $specialoffers[0]->thumbnail;?>">
        </a>
        </div>
    </div>
    <div class="col-md-12">
        <h3 class="offh3"><strong class="ttu"><?php echo character_limiter($specialoffers[0]->title,30);?></strong></h3>
        <p class="offp">
            <?php echo character_limiter($specialoffers[0]->desc,240);?>
            <a href="<?php echo base_url(); ?>offers" >
            Read More
            </a>
        </p>
    </div>
</div>
<?php } ?>

当我尝试以下更改时,页面崩溃了,并且出现了此错误

  

[2018年8月12日13:48:09 UTC] PHP致命错误:无法使用类型的对象   stdClass作为数组   /home/bannabooking/public_html/beta/themes/default/views/home/index.php   在第152行

更改代码:

<?php foreach($specialoffers as $offer) if ($tmp++ < 3) { ?>
<div class="col-md-4">
    <div class="col-md-12">
        <?php if($offer[0]->price > 0){ ?> <span class="wow bounce ttu"><?php echo trans('0536');?> <b><?php echo trans('0388');?></b> <small><?php echo $offer[0]->currCode;?></small> <?php echo $offer[0]->currSymbol; ?><?php echo $offer[0]->price;?></span>
        <?php } ?>
        <div class="imgLodBg">
        <div class="load"></div>
        <a href="<?php echo base_url(); ?>offers">
        <img data-wow-duration="0.2s" data-wow-delay="1s" class="wow fadeIn" src="<?php echo $offer[0]->thumbnail;?>">
        </a>
        </div>
    </div>
    <div class="col-md-12">
        <h3 class="offh3"><strong class="ttu"><?php echo character_limiter($offer[0]->title,30);?></strong></h3>
        <p class="offp">
            <?php echo character_limiter($offer[0]->desc,240);?>
            <a href="<?php echo base_url(); ?>offers" >
            Read More
            </a>
        </p>
    </div>
</div>
<?php } ?>

1 个答案:

答案 0 :(得分:2)

foreach () {}内部,您已经具有单个$offers对象。因此,您无需直接通过$offer[0]->price访问它们,而是需要直接访问每个$offer->price$offer->desc等。

通常,foreach () {}方法如下:

$offers = [new Offer('a'), new Offer('b')];
foreach ($offers as $offer) {
    // $offer here sequentially corresponds 
    // to each element of the $offers array
    echo $offer->price;
}

$offers数组上完成迭代的另一种方法可能是这样的:

$offers = [new Offer('a'), new Offer('b')];
for ($i = 0; $i < array_length($offers); $i++) {
    echo $offers[$i]->price;
} 

因此,您只需要坚持使用这些方法之一。通常foreach看起来更准确。