2016-12-02 89 views
-2

如何才能让此foreach线路只显示第一个结果?只显示第一个结果的Foreach显示

<?php foreach ($collection as $product) : ?> 

我试过了以下,但那不起作用。它比不显示任何结果:

<?php foreach (array_slice($collection, 0, 1) as $product) : ?> 

编辑:

完善以下工作:

<?php 
$i = 0; 
foreach ($collection as $product) : 
    if($i < 1) { 
     Inner content 
    } 
    $i++; 
endforeach; 
?> 

总电流代码:

<tbody> 
    <tr> 
     <td class="image" rowspan="3">  
     <?php $i = 0; foreach ($collection as $product) : if($i < 1) {?> 
      <img src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(75) ?>" alt="<?php echo $this->htmlEscape($product->getName()) ?>" width="75" height="75" /> 
     <?php } $i++; endforeach ?> 
     </td> 
     <td class="order" colspan="2">order</td> 
     <td class="exclTax">excl. vat</td> 
     <td class="inclTax">incl. vat</td> 
    </tr>      

    <?php foreach ($collection as $product) : ?> 
    <tr> 
     <td class="select"><input type="radio" name="featured_1807" id="featured_1807_1349567899" value="3071895, IM" data-product-id="3071895" data-product-sup="IM"></td> 
     <td class="title"><a href="<?php echo $abstractBlock->getProductUrl($product) ?>" class="" tooltip="" title=""><?php echo $this->htmlEscape($product->getName()) ?></a></td> 
     <td class="price"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td> 
     <td class="priceIncl"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td> 
    </tr> 
    <?php endforeach ?> 
</tbody> 

我怎样才能做到这一点?

+1

应该正常工作。请提供给我们一个[mcve] – Rizier123

+0

问题出在你运行INSIDE的foreach代码中,而不是在foreach线本身**显示更多代码** – RiggsFolly

+1

想想吧,如果你只想要第一次出现,根本不管用。为什么不使用'$ collection [0]' – RiggsFolly

回答

1

为什么用循环打扰,如果你只关心的$collection

第一次出现你能做到这一点,而不是,可能没有改变你的循环内您目前拥有的任何代码

<?php 

$product = $collection[0]; 

Code you had in the loop 
?> 

如果它不是一个数字键,那么你可以使用

<?php 
reset($collection); // make sure you are on first occ 
$product = $collection[key($collection)]; 

... html stuff 

// and then do again for your second loop 
// if you only want the first occ of that as well 

reset($collection); // make sure you are on first occ 
$product = $collection[key($collection)]; 
+0

谢谢。我尝试了以下,但这不起作用:'??php $ product = $ collection [0]; ?> \t \t \t

+1

In什么方法_不工作_有很多事情在那行代码 – RiggsFolly

+0

在前端获取以下php错误:'致命错误:未捕获错误:不能使用AW_Autorelated_Model_Product_Collection类型的对象' –

0
reset($collection); // Resets the array's internal pointer to the first element 
$product = current($collection); // Returns the current element which is now first element 

就我而言,如果我只需要从数组中提取第一个元素,那么这将是最好的解决方案。

+0

您是否知道'reset'还会返回第一个元素? –

+0

@ Don'tPanic没有。谢谢你让我知道! – Perumal