Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

php - sort Magento collection AFTER load

The Magento collection sorting functions (e.g. Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToSort) work by adding an ORDER BY clause to the SQL select statement. However, there are times when a collection has already been loaded and it is necessary to sort the collection.

It is certainly possible to use the toArray($fields) function and then PHP array sorting functions (either native or user-defined), however this is a little clumsy. It also means that the objects in the collection are converted to "dumb" rows of values without magic getters/setters which can/are be implemented with algorithms, etc.

I'm wondering if there are more elegant/Magento-esque methods of sorting the collection.

Thanks,
Jonathan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no proper way of doing it. But I think it is possible with using of Reflection. You can retrieve $_items property of collection object, sort them and set it back to the collection.

function sortCollection(Varien_Data_Collection $collection, callable $sorter) {
    $collectionReflection = new ReflectionObject($collection);
    $itemsPropertyReflection = $collectionReflection->getProperty('_items');
    $itemsPropertyReflection->setAccessible(true); // Make it accessible

    $collectionItems = $itemsPropertyReflection->getValue($collection);

    usort($collectionItems, $sorter);

    $itemsPropertyReflection->setValue($collection, $collectionItems);

    $itemsPropertyReflection->setAccessible(false); // Return restriction back

    return $collection;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...