I have an array full of objects from the same class. I’d like to sort this array by optional object field, for instance $case->ID or $case->Sender
Is there a built in flavor of the array_sort() function that does this already, or will I have to write this sort function myself?
Answer doesn’t have to explain in detail – this is more like a yes/no question
Thanks
My failed attempt at usort:
function sortBy($sort)
{
usort($this->abuseCases, function($a, $b) {
if($a->{$sort} > $b->{$sort}) return 1;
if($a->{$sort} < $b->{$sort}) return -1;
else return 0;
});
}
Another failed attempt:
function sortBy($sort)
{
$this->sortBy = $sort;
usort($this->abuseCases, array("this", "srt"));
}
private function srt($a, $b)
{
if($a->{$this->sortBy} > $b->{$this->sortBy}) return 1;
if($a->{$this->sortBy} < $b->{$this->sortBy}) return -1;
else return 0;
}
Edit for bump
You can use not only an anonymous function but a closure, like e.g.
and $sort will be available in the function body.
Self-contained example:
prints
Update: With php<5.3 you can use an object instead of an anonymous function.
usort() expects the second parameter to be a
callable. That can be an anoymous function as of php 5.3, but it can also be the name of a function ….or an object and a method name passed as an array likearray($obj, 'methodName').(If you make heavy use of this – or don’t want to write excuses like this one -_- – you might want to define an interface like
interface Comparator { ... }, let Foo implement that interface and have some function/class that uses Comparator, i.e. a wrapper for objects around usort().)