我想循环思考添加到购物车中的所有商品并返回它自己的 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;
}
现在它返回一行中的所有内容,因此我的结果是这样的,我应该使用“,”来拆分它们吗?
P.S: 我编辑的文件是\app\code\core\Mage\Checkout\Helper下的Data.php
我假设第一个产品的 ID 是 471186,第二个产品的 ID 应该是 463089,我是否需要另一个 foreach 循环来做到这一点?
更新2:即使我拆分它,它也只会显示为 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 表示 null。
所以我像这样重构我的代码:
$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'];
}
关于javascript - 循环浏览购物车商品并返回它自己的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383013/