2016-12-02 171 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