We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Reorder a resultset

Is there a way to reorder a resultset by a specific criteria?

$robots = Robots::find(); $robots->ReorderBy()->getFullName();



2.6k

Not with the resultset itself. You need to convert it to an array and sort that using a costum callback function which desides the order.

$robotsArray = iterator_to_array($robots);
uasort($robotsArray, function($a, $b){

    //Custom callable which re-orders
    if ($a == $b) {
        return 0;
    }
    return ($a->id < $b->id) ? -1 : 1;
});

find() can accept arguments, so if you want to have your resultset ordered in a particular way, you can do this:

$robots = Robots::find(['order'=>'full_name']);

If you want to change the order of a resultset that has already been retrieved, you'll have to do what @waaghals suggested.