How to Sort Product Collection by Array Key in Magento

collection-filteringcollection;productproduct-collectionsorting

I am trying to sort a product collection by SKU based on the order that the SKUs appear in the $skus array passed into the addAttributeToFilter method in the collection below:

    $skus = explode(",",$this->getRequest()->getParam('skus'));

    $collection = Mage::getModel('catalog/product')->getCollection()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('sku',array('in'=>$skus))
                    ->addAttributeToFilter('visibility',array('gt'=>array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)))
                    ->addAttributeToFilter('status',array('eq'=> Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
                    ->addUrlRewrite()
    ;

How can I sort this collection so that the products appear in the same order as their skus inside the $skus array?

Best Answer

I have done something similar using the MySQL FIELD() function. Maybe it can also help you here.

After you have added the other filters to your collection, call this:

$collection->getSelect()->order(new Zend_Db_Expr('FIELD(sku, "' . implode('","', $skus) . '") DESC'));