简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM