加载后对 Magento 集合进行排序 [英] sort Magento collection AFTER load
问题描述
Magento 集合排序函数(例如 Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToSort
)通过将 ORDER BY
子句添加到 SQL 选择语句来工作.但是,有时已经加载了集合并且需要对集合进行排序.
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.
当然可以使用 toArray($fields)
函数,然后使用 PHP 数组排序函数(本机或用户定义的),但这有点笨拙.这也意味着集合中的对象被转换为哑"值行,没有可以/可以用算法等实现的魔法 getter/setter.
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.
我想知道是否有更优雅/Magento 风格的方法来对集合进行排序.
I'm wondering if there are more elegant/Magento-esque methods of sorting the collection.
谢谢,
乔纳森
推荐答案
另一种有效的解决方案:
Another solution which works:
class Aligent_Navigation_Block_Dropdown extends Mage_Catalog_Block_Product_List {
public function getProductsByShortDesc(){
$data = $this->getLoadedProductCollection()->getItems(); //an array of objects
usort($data,array('Aligent_Navigation_Block_Dropdown','sortByShortDesc'));
return $data;
}
public static function sortByShortDesc($a, $b)
{
if($a->getShortDescription() == $b->getShortDescription()){ return 0 ; }
return ($a->getShortDescription() < $b->getShortDescription()) ? -1 : 1;
}
}
这篇关于加载后对 Magento 集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!