php – 颠倒Doctrine_Collection的顺序
发布时间:2020-12-13 16:40:30 所属栏目:PHP教程 来源:网络整理
导读:我正在寻找一个干净的方式来扭转Doctrine_Collection的顺序. 我知道这听起来很奇怪,所以让我解释一下我的(简单的)目标:我需要显示x最新/最新的记录,但是我必须按相反的顺序显示:最旧的1等 如果不清楚,这里是一个例子: 让我说我有这个在我的表(让我们称之
|
我正在寻找一个干净的方式来扭转Doctrine_Collection的顺序.
我知道这听起来很奇怪,所以让我解释一下我的(简单的)目标:我需要显示x最新/最新的记录,但是我必须按相反的顺序显示:最旧的1等 如果不清楚,这里是一个例子: 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亲吻回答 $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);
}
希望好回答: 您可以将集合导出到数组并将其反转 $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);
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
