我正在寻找一种干净的方法来反转 Doctrine_Collection 的顺序。 我知道这听起来很奇怪,所以让我解释一下我的(简单)目标:我需要显示 x 最新/最新 记录,但我必须以相反的顺序显示它:最旧的第一等
如果还不清楚,这里有一个例子: 假设我的表中有这个(我们称之为“示例”):
id date
1 2012-01-21
2 2012-03-19
3 2012-02-21
4 2012-03-21
到目前为止,我已经这样做了:
Doctrine::getTable('Example')->createQuery('d')
->orderBy('date DESC')
->limit(3);
返回结果
id date
4 2012-03-21
2 2012-03-19
3 2012-02-21
但我想要这样:
id date
3 2012-02-21
2 2012-03-19
4 2012-03-21
<小时/>
编辑:
我找到了一个解决方案,使用中间数组并使用 array_reverse 。但看起来不太好:(
这是我编写的代码:
$query = Doctrine::getTable('Example')
->createQuery('e')
->orderBy('date DESC')
->limit(3)
$collection = $query->execute();
//Here is the dirty hack:
$itemArray = array();
foreach ($collection as $item) {
$itemArray[] = $item;
}
$itemArray = array_reverse($itemArray);
$orderedCollection = new Doctrine_Collection($doctrineClass);
foreach($itemArray as $item) {
$orderedCollection->add($item);
}
//OrderedCollection is OK but... come on! There must be a cleaner way to do it
<小时/>
编辑 2:@Adam Kiss 的回答
$query = Doctrine::getTable('Example')
->createQuery('e')
->orderBy('date DESC')
->limit(3)
$collection = $query->execute();
//Here is the **lovely** hack:
$orderedCollection = new Doctrine_Collection('Example');
for ($i=($collection->count() - 1); $i>=0;$i--) {
$orderedCollection->add($collection->get($i));
}
最佳答案
没有中间数组:
for ($i = $collection->count(); $i > 0; $i--) {
$orderedCollection->add($collection->get($i));
}
希望有好的答案:
您可以将 Collection 导出到数组并反转它
$query = Doctrine::getTable('Example')
->createQuery('e')
->orderBy('date DESC')
->limit(3)
$collection = $query->execute();
$collection = array_reverse($collection->toArray());
旧(错误)答案:
也许你应该使用
Doctrine::getTable('Example')->createQuery('d')
->orderBy('date ASC')
->limit(3);
关于php - 反转 Doctrine_Collection 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9802940/