[英]loop through the cart items and return it's own ID
我想循環考慮添加到購物車中的所有物品並返回其自己的ID。
UPDATE1 :我已經更新了這樣的方法
public function formatPrice($price)
{
$productId=""; // an iterate here
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productId = $item->getProduct()->getId();
$productPrice = $item->getProduct()->getFinalPrice();
}
return 'ID: '.$productId;
}
現在它返回所有內容,因此我得到了這樣的結果,是否應該使用“,”來分割它們?
PS:我正在編輯的文件是\\ app \\ code \\ core \\ Mage \\ Checkout \\ Helper下的Data.php
我假設第一個產品的ID為471186,第二個產品的ID為463089,我是否需要另一個foreach循環來做到這一點?
UPDATE2:即使我拆分了它,它也會像471186、463089一樣顯示,但是我希望它根據當前的產品顯示,我確定我還需要其他東西,magento庫是否提供了類似的方法?
UPDATE3:我看過您的最新方法,該方法將變量存儲在數組中並返回它。 經過一些修改取決於您的代碼,我有:
$productId =array();
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach($cart->getAllItems() as $item) {
$productId[]= $item->getProduct()->getId();
}
$productId =array_filter($productId);
//remove empty array
foreach($productId as $id){
return $id; //return $productId;
}
如果我使用return $ productId ,它給我“ Array”數據類型作為結果,這是沒有用的,我嘗試打印出$ id,它只像以前一樣給出第一個產品ID。 在這種情況下,我將使用print_r,但似乎不允許我這樣做。
UPDATE4:我嘗試了內部的for循環,並且我假設它將循環並顯示價格,直到其值小於$ index,即0表示空。
所以我像這樣重構我的代碼:
$productId =array();
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach($cart->getAllItems() as $item) {
$productId['id']= $item->getProduct()->getId();
$productId['price'] = $item->getProduct()->getFinalPrice();
}
$productId =array_filter($productId);
for($index=0; $index<count($productId); $index++){
return $productId[$index]['price']; //cannot use echo, printf and print_r
}
但是它返回的僅是null,購物車上沒有任何內容。
在一個函數中,您只能返回一個值。 您應該將每次迭代的結果連接起來,然后返回
$productId= "";
foreach($cart->getAllItems() as $item) {
$productId.= $item->getProduct()->getId();
$productPrice = $item->getProduct()->getFinalPrice();
}
return 'ID: '.$productId;
或使用數組
$productId =array();
foreach($cart->getAllItems() as $item) {
$productId['id']= $item->getProduct()->getId();
$productId['price'] = $item->getProduct()->getFinalPrice();
}
$productId =array_filter($productId);
//remove empty array
for($index=0; $index<count($productId); $index++){
echo $productId[$index]['id'];
echo $productId[$index]['price'];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.