Magento Custom Collection Sorting | Magento sort collection Item

Magento Custom Collection Sorting | Magento sort collection Item

function sortMagentoCollection(Varien_Data_Collection $collection, callable $sorter) {

$collectionReflectionMirror = new ReflectionObject($collection);
$itemsPropertyReflection = $collectionReflectionMirror->getProperty(‘_items’);
$itemsPropertyReflection->setAccessible(true);
$collectionItems = $itemsPropertyReflection->getValue($collection);
usort($collectionItems, $this->sorterCmp($sorter));
$itemsPropertyReflection->setValue($collection, $collectionItems);

$itemsPropertyReflection->setAccessible(false);

return $collection;
}

function sorterCmp($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}

example :

just call the method : sortMagentoCollection($collection,$sorter);

where $collection which you want to sort
$sorter : key name to sort , it may me column name on the basis of which you want to sort.


Advertisements

Add Comment

📖 Read More