hal*_*ush 12 php doctrine symfony-1.4
我正在寻找一种干净的方式来扭转Doctrine_Collection的顺序.我知道这听起来很奇怪,所以让我解释一下我的(简单)目标:我需要显示x 最新/最新的记录,但我必须以相反的顺序显示它:最老的第1个等等.
如果不清楚,这是一个例子:让我说我在我的表中有这个(让我们称之为'示例'):
id date
1 2012-01-21
2 2012-03-19
3 2012-02-21
4 2012-03-21
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经这样做了:
Doctrine::getTable('Example')->createQuery('d')
->orderBy('date DESC')
->limit(3);
Run Code Online (Sandbox Code Playgroud)
哪个回来了
id date
4 2012-03-21
2 2012-03-19
3 2012-02-21
Run Code Online (Sandbox Code Playgroud)
但我希望如此:
id date
3 2012-02-21
2 2012-03-19
4 2012-03-21
Run Code Online (Sandbox Code Playgroud)
编辑:
我找到了一个解决方案,使用中间数组并使用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
Run Code Online (Sandbox Code Playgroud)
编辑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));
}
Run Code Online (Sandbox Code Playgroud)
Ada*_*iss 16
for ($i = $collection->count(); $i > 0; $i--) {
$orderedCollection->add($collection->get($i));
}
Run Code Online (Sandbox Code Playgroud)
您可以将Collection导出到数组并将其反转
$query = Doctrine::getTable('Example')
->createQuery('e')
->orderBy('date DESC')
->limit(3)
$collection = $query->execute();
$collection = array_reverse($collection->toArray());
Run Code Online (Sandbox Code Playgroud)
也许你应该使用
Doctrine::getTable('Example')->createQuery('d')
->orderBy('date ASC')
->limit(3);
Run Code Online (Sandbox Code Playgroud)
您似乎要么自定义Doctrine_collection以提供类似于array_reverse
集合类的内容,要么使用如下的一些hackish方法:
$keys = array_reverse($collection->getKeys());
foreach ($keys as $key) {
$object = $collection->get($key);
}
Run Code Online (Sandbox Code Playgroud)
如果您不想使用任何特殊的集合功能,只需按相反的顺序迭代元素(没有任何开销),您可以这样做非常简单:
/** @var $results Doctrine_Collection this is your result collection */
$iterator = $results->getIterator();
$item = end($iterator);
do {
var_dump($item);
} while ($item = prev($iterator));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15815 次 |
最近记录: |