I am trying to create a block which shows the 5 top selling products, 5 most viewed products and 5 largest discounted products on a Magento 1.7.0.2 site.
The block is defined as follows in local.xml:
<reference name="content">
<block type="core/template" name="movies_block" template="catalog/product-block.phtml" before="-">
<action method="setData"><name>category_id</name><value>5</value></action>
</block>
</reference>
(you pass it a category id, the idea being it can be quickly reused throughout my theme for categories of my choosing)
I have written and tested code for displaying top sellers and most viewed, but I'm struggling with a way to efficiently sort the top 5 most discounted. I'm defining a discount as the % difference between 'price' and 'special_price'.
My code for this is as follows:
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
);
$catNum = $this->getCategoryId(); // grab cat id from xml
$category = Mage::getModel('catalog/category')->load($catNum);
// load products from $category
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->addCategoryFilter($category);
$saleProducts = array();
$i=0;
foreach($_productCollection as $product):
if($product->getSpecialPrice()): // if a product has a special price
/* calculate discount as percentage and add it to $product array of each */
$product['discount'] = $product->getSpecialPrice()/$product->getPrice()*100;
$saleProducts[$i] = $product; // put discounted products into separate array
$i++;
endif;
endforeach;
This leaves an array $saleProducts, of products which have a 'special_price'. However, I want just the top 5 most discounted (highest value in $product['discount'] first).
I've been attempting to sort the array using:
function cmp($a, $b) {
return ($a['discount'] - $b['discount']);
}
usort($saleProducts, "cmp");
But as soon as I add anything to my code with 'function' in it, the whole block no longer displays... happens even if I just write:
function sortByDiscount($a, $b) {};
anywhere in the .phtml file, is Magento preventing me from creating a function? Anybody else tackled this particular problem? I have a feeling my way might be quite slow, especially since I used other product collections with filters earlier on in the same .phtml file, and this block needs to work with categories of up to 20,000 products.
Any suggestions welcome.