Jon*_*Day 6 php arrays sorting collections magento
Magento集合排序函数(例如Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToSort)通过向ORDER BYSQL select语句添加子句来工作.但是,有时候已经加载了一个集合,并且有必要对集合进行排序.
当然可以使用该toArray($fields)函数,然后使用PHP数组排序函数(本机或用户定义),但这有点笨拙.这也意味着集合中的对象被转换为"哑"值的行,而没有可以/可以用算法等实现的魔法getter/setter.
我想知道是否有更优雅/ Magento-esque方法对系列进行排序.
谢谢,
乔纳森
Iva*_*nyi 12
没有正确的方法.但我认为使用反射是可能的.您可以检索集合对象的$ _items属性,对它们进行排序并将其设置回集合.
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;
}
Run Code Online (Sandbox Code Playgroud)
另一个有效的解决方案:
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;
}
}
Run Code Online (Sandbox Code Playgroud)