0

If there's a way in Magento 2 to get the average price for a product collection.

Or should I loop over the collection?

Thanks

2

I would do a loop through each of the products, have a count and a sum and then work out the average.

When your looping through your products remember to have a second loop to check if it is a configurable too to make sure you don't skip the simples.

something maybe like this :

$count = 0;
                $sum = 0;
                foreach ($configurableCollection as $product) {

                    $parentProductId = $product->getId();

                    if($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
                        $_children = $product->getTypeInstance()->getUsedProducts($product);

                        foreach ($_children as $child) {
                            $productPrice = $child->getPrice();
                            $sum = ($sum + $productPrice);
                        }
                        
                    } else {
                        $productPrice = $product->getPrice();
                        $sum = ($sum + $productPrice);
                    }

                    $count++;

                }

                $average = ($sum / $count);
4
  • Can you please tell me what is the use of $parentProductId = $product->getId();?
    – AboElnouR
    Jun 28 '21 at 20:54
  • In Magento 2.4.2, it shows all configurable child production in the main loop, so I don't think we need two loops here, just skip the configurable.
    – AboElnouR
    Jun 29 '21 at 9:42
  • @AboElnouR it is to go through the simple products of the configurables, if your over 2.4.2 then maybe your simple products are already in the main loop. I would put a logger in the loop so you can see exactly whats in your product collection : $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logger.log'); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $logger->info($product->getName());
    – Gaz Smith
    Jul 1 '21 at 8:17
  • @AboElnouR it is to go through the simple products of the configurables, if your over 2.4.2 then maybe your simple products are already in the main loop. I would put a logger in the loop so you can see exactly whats in your product collection : $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logger.log'); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $logger->info($product->getName());
    – Gaz Smith
    Jul 1 '21 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.