Magento Checkout 计算符合属性的产品的重量

Magento Checkout count weight of products which match attribute

我需要计算结账时有多少特定类型的产品。但只有(!)特定类型的产品。类型在下拉属性中定义。

这是一个计算重量的代码,效果很好。 \template\checkout\cart.phtml

<?php $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$weight = 0;
foreach($items as $item) {
    $weight += ($item->getWeight() * $item->getQty()) ;
}
echo $weight;
?>

但是如何只计算具有特定属性值的产品?

赞 => "count only products which have Attribute color = green"

我发现了很多关于收集和过滤的信息,但它似乎不适用于购物车项目。

希望你能帮助我。

这是获取属性值的方法(加载产品后):

 $product = $item->getProduct();
 $value = $product->getAttributeText($yourAttributeCode);

但是请注意,您需要将 'Show in Product Listing''Used in Product Listing' 设置为是的,在管理面板的属性编辑器中。


对于分组部分,一种可能的方法是做这样的事情(只有当您的特定属性的值数量很少时才有意义):

$weights = array ('redWeight' => 0, 'blueWeight' => 0, 'yellowWeight' => 0, ..);
$groupRed = array();
$groupGreen = array();
 ...

foreach($items as $item) {
  $product = $item->getProduct();
  $value = $product->getAttributeText('yourAttributeCode');
  $weight = ($item->getWeight() * $item->getQty());
  if($value){ //Do all products have this attribute?
    Switch($value){
       case "red":
           $Weights['redWeight'] += $weight;
           $groupRed[] = $item;
           break;
       case "green":  
          ....
     }
  } else {
    continue;
   } 
}
 ....
  HERE YOU HAVE GROUPS OF YOUR ITEMS ACCORDING TO THEIR SPECIFIC ATTRIBUTE VALUES

您必须在循环时加载产品模型(昂贵),然后您可以像这样调用它的属性:

foreach( $oItems as $oItem )
{
    $oProduct = $oItem->getProduct();
    $oProductModel = Mage::getModel( 'catalog/product' )->load( $oProduct->getId() );
    // For code...
    $sColor   = $oProductModel->getData( 'color' );
    var_dump( $sColor );
    // For text...
    $sFormat  = $oProductModel->getAttributeText( 'color' );
    var_dump( $sFormat );
}