pidari pidari - 3 years ago 193
PHP Question

Sorting by value higher to lower in array of objects

I have an array of objects that I need to sort by highest salary. I know I should use a user defined sorting function but not sure which one and how to do it. Here is my array:

array(4) {
[0]=>
object(Employee)#1 (6) {
["name"]=>
string(5) "Pesho"
["salary"]=>
string(6) "120.00"
["position"]=>
string(3) "Dev"
["department"]=>
string(11) "Development"
["email"]=>
string(12) "pesho@abv.bg"
["age"]=>
int(28)
}
[2]=>
object(Employee)#3 (6) {
["name"]=>
string(4) "Ivan"
["salary"]=>
string(6) "840.20"
["position"]=>
string(13) "ProjectLeader"
["department"]=>
string(11) "Development"
["email"]=>
string(13) "ivan@ivan.com"
["age"]=>
int(-1)
}
}


Ivan needs to be before Pesho.

Answer Source
usort($array, function($a, $b) {
    if ($b == $a) {
        return 0;
    }
    return ($b < $a) ? -1 : 1;
});

usort — Sort an array by values using a user-defined comparison function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download