Note that there are some explanatory texts on larger screens.

plurals
  1. POReverse the order of a Doctrine_Collection
    primarykey
    data
    text
    <p>I'm looking for a clean way to reverse the order of a Doctrine_Collection. I know it sounds weird, so let me explain my (simple) goal: I need to display the x <strong>latest/newest</strong> record, but I have to display it in the reverse order: the <strong>oldest 1st</strong>, etc.</p> <p>If it's unclear, here is an example : Lets say I have this in my table (lets call it 'example') :</p> <pre><code>id date 1 2012-01-21 2 2012-03-19 3 2012-02-21 4 2012-03-21 </code></pre> <p>So far, I've done this:</p> <pre><code>Doctrine::getTable('Example')-&gt;createQuery('d') -&gt;orderBy('date DESC') -&gt;limit(3); </code></pre> <p>Which returns that</p> <pre><code>id date 4 2012-03-21 2 2012-03-19 3 2012-02-21 </code></pre> <p>But I want that:</p> <pre><code>id date 3 2012-02-21 2 2012-03-19 4 2012-03-21 </code></pre> <hr> <p>Edit:</p> <p>I've found a solution to this, using intermediate array &amp; using array_reverse on it. But it doesn't look good :(</p> <p>Here is the code I've written:</p> <pre><code> $query = Doctrine::getTable('Example') -&gt;createQuery('e') -&gt;orderBy('date DESC') -&gt;limit(3) $collection = $query-&gt;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-&gt;add($item); } //OrderedCollection is OK but... come on! There must be a cleaner way to do it </code></pre> <hr> <p>Edit 2 : answer from @Adam Kiss</p> <pre><code> $query = Doctrine::getTable('Example') -&gt;createQuery('e') -&gt;orderBy('date DESC') -&gt;limit(3) $collection = $query-&gt;execute(); //Here is the **lovely** hack: $orderedCollection = new Doctrine_Collection('Example'); for ($i=($collection-&gt;count() - 1); $i&gt;=0;$i--) { $orderedCollection-&gt;add($collection-&gt;get($i)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload