在加载后对Magento系列进行排序

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)

  • 我确认Ivan是可能的,我的合作伙伴只是成功使用你的代码片段.唯一的问题是,而不是`$ collection-> getProperty('_ items');`他必须使用`$ collectionReflection-> getProperty('_ items');`,我猜是一个小错字.我认为值得一说的另一件事是,当我们谈论Magento,因此我们讨论Classes时,`$ yourSortingCallback`必须是一个包含2个元素的数组,第一个是定义方法的类的名称,第二个是方法的名称,即:`usort($ collectionItems,array('The_Class','The_Method'));`.无论如何,我们都非常感谢 (3认同)

Jon*_*Day 2

另一个有效的解决方案:

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)