Magento - Collection Filter by Array Keep Order
magento
Solution
$productIds = array(1,3,2);
/**
* Build up a case statement to ensure the order of ids is preserved
*/
$orderString = array('CASE e.entity_id');
foreach($productIds as $i => $productId) {
$orderString[] = 'WHEN '.$productId.' THEN '.$i;
}
$orderString[] = 'END';
$orderString = implode(' ', $orderString);
/**
* Filter the collection
*/
$productCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productIds));
/**
* Apply the order based on the case statement
*/
$productCollection->getSelect()
->order(new Zend_Db_Expr($orderString))
Problem
Is it possible to filter a Magento collection using an array of id's BUT have the collection results ordered by the order of the id's passed to the filter. For example: ``` $collection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToFilter('entity_id', array( 'in' => array(1, 3, 2), )); ``` I would like the collection to have products in order, 1,3,2 so as when looping through the collection they come out in that specific order? The only alternative i currently have is to manually create an array of products: ``` $productIds = array(1,3,2); $collection = array(); foreach($productIds as $productId) { $collection[] = Mage::getModel('catalog/product')->load($productId); } ``` This obviously works but seems like an ugly way to do this. is there a way to do this purely via magento collections?