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
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);