Skip to content

Sorting PHP arrays of objects by an object property

Much of the time when you are working on web applications, you’ll be working with arrays of data. And frequently those arrays (or Collections) will be populated with objects. And sometimes you’ll want to sort those arrays by an arbitrary property on the objects it contains. This is where the usort function comes into it’s own…

For usort to work, you need to specify a function/method to perform the comparison, and that function needs to return -1,0 or 1.


class MyClass
{
public static function MySort( $a, $b)
   {
        if($a->property == $b->property) return 0;
        if( $a->property > $b->property){
           return 1;
        }else{
           return -1;
        }
    }
}

// Using it...
$collection = MyClass::fetchAll();
usort($collection, array("MyClass", "MySort"));

Obviously you can put more interesting logic into your MySort function. If you’re sorting on dates, you’ll want to do some DateTime object comparisons, for example.

Now you’re almost certainly wondering why you don’t add the sort into the ::fetchAll method, but sometimes you don’t have easy access to modify the API, and hence need to find workarounds…

This entry was posted in Web Development. Bookmark the permalink.

Comments

Sorry, comments are closed on this page.