php - 反转 Doctrine_Collection 的顺序

标签 php doctrine symfony-1.4

我正在寻找一种干净的方法来反转 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/

相关文章:

php - 如何从laravel Controller 传递搜索查询到elasticsearch?

php - 为什么 Doctrine 返回的字段比我要求的多?

mysql - 与不是主键的外键(主键是 auto_increment 'id' )与doctrine2/symfony2 的 1-N 关系

php - Doctrine 和 Symfony 中的 MySQL 用户定义变量

php - 我们如何配置 symfony 1.4 以与 Varnish 一起使用?

php - FPDF错误: Unsupported image type: image/jpeg

PHP - 多维数组合并为一个数组

php - 识别 Twig 变量中的空白

symfony - Doctrine 事件监听器和软删除过滤器

php - Symfony - 更新唯一列 - 验证问题