3

How do I find the max weight and min weight of a category with 3000 products.

enter image description here

enter image description here

I'm trying use:

public function getProductCollectionFilter($_productCollection)
{
    $_productCollection = $this->_currentCategory->getProductCollection();
    Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_productCollection);
    $weights = array();
    foreach ($_productCollection as $product) {
        $_product = Mage::getModel('catalog/product')->load($product->getId());
        $weight = $_product->getAttributeText('karma_weight');
        if (strpos($weight, 'kg') !== false) {
            $weight = str_replace('kg', '', $weight);
            $weight = (int) $weight;
            $weight = $weight * 1000;
        }
        $weight = str_replace('g', '', $weight);
        $weight = (int) $weight;
        $weights[] = $weight;
    }
    return $weights;
}

and:

public function getMaxRangeWeight()
{
    $maxWeight = 0;
    $_productCollection = $this->_currentCategory->getProductCollection();
    $weights = $this->getProductCollectionFilter($_productCollection);
    foreach ($weights as $weight){
        if ($weight > $maxWeight) $maxWeight = $weight;
    }
    return $maxWeight;   
}

That work. But with a category have 500 -> 3000 product the page can't load.

sv3n
  • 11,657
  • 7
  • 40
  • 73

1 Answers1

3

Maybe this works for you:

$collection = Mage::getModel('catalog/category')
    ->load(41) // your category ID
    ->getProductCollection()
    ->addAttributeToSelect('weight');

$func = function($weight) {
    if (strpos($weight, 'kg') !== false) {
        return (int) str_replace('kg', '', $weight) * 1000;
    } else {
        return (int) str_replace('g', '', $weight) * 1;
    }
};

$weights = array_map($func, $collection->getColumnValues('weight'));
asort($weights);

// min
var_dump(reset($weights));

// max
var_dump(end($weights));

Edit:

I guess the problem is this full product load used in a foreach loop:

$_product = Mage::getModel('catalog/product')->load($product->getId());

Instead add weight attribute to your collection before:

$collection->addAttributeToSelect('weight');

and in loop

$weight = $product->getData('weight');

Impact: for 750 products

With Mage::getModel('catalog/product')->load($product->getId())

  • Total Incl. Wall Time (microsec): 127,890,913 microsecs
  • Total Incl. CPU (microsecs): 126,421,753 microsecs
  • Total Incl. MemUse (bytes): 26,251,496 bytes
  • Total Incl. PeakMemUse (bytes): 26,367,680 bytes
  • Number of Function Calls: 6,097,472

Usage of addAttributeToSelect('weight'):

  • Total Incl. Wall Time (microsec): 2,224,265 microsecs
  • Total Incl. CPU (microsecs): 2,204,274 microsecs
  • Total Incl. MemUse (bytes): 4,893,728 bytes
  • Total Incl. PeakMemUse (bytes): 4,412,616 bytes
  • Number of Function Calls: 107,932
sv3n
  • 11,657
  • 7
  • 40
  • 73