用于排序 Doctrine ArrayCollection 的 Twig 扩展 [英] Twig extension for sorting Doctrine ArrayCollection
问题描述
我正在尝试编写一个 Twig 过滤器,以便能够对 Doctrine ArrayCollection 进行排序,但返回的数组未排序:( 请您帮我解决这个问题:
I'm trying to write a Twig filter to be able to sort a Doctrine ArrayCollection, but the returned array is not sorted :( Can you please help me to fix this:
class SortExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('sortby', array($this, 'sortByFilter')),
);
}
public function sortbyname( $a, $b )
{
if ($a->getName() === $b->getName()) {
return 0;
}
if ( $a->getName() < $b->getName() ) {
return 1;
}
return -1;
}
public function sortByFilter($collection)
{
$iterator = $collection->getIterator();
$iterator->uasort(array($this, 'sortbyname'));
return $collection;
}
我不太确定 sortByFilter 中返回的集合是否已更改.
I'm not quite sure if the returned collection in sortByFilter is changed.
推荐答案
这是因为您正在获取迭代器并对其进行排序.
方法 getIterator
创建一个新的 ArrayIterator
来制作数组的副本.
然后,您将返回未排序的集合.
This is because you are getting the iterator and sorting it.
The method getIterator
creates a new ArrayIterator
which makes a copy of the array.
Then, you are returning the collection, which is not sorted.
这是发生的事情的一个小例子.
Here is a little sample of what happens.
你只需要更换
return $collection;
通过
return $iterator;
这篇关于用于排序 Doctrine ArrayCollection 的 Twig 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!