Sort array by object property in PHP?

前端 未结 15 900
萌比男神i
萌比男神i 2020-12-04 12:07

If I have an object as such:

class Person {
  var $age;
  function __construct($age) {
    $this->age = $age;
  }
}

and I have any array

15条回答
  •  心在旅途
    2020-12-04 12:28

    If all member variables in question are guaranteed to be different, it will be simpler and faster to create a new collection indexed by these values and then ksort it:

     foreach($obj_list as $obj)
        $map[$obj->some_var] = $obj;
     ksort($map);
     /// $map now contains the sorted list
    

    If there are duplicate values, you can still avoid usort by utilizing a less known feature of sort that arrays of arrays are sorted by the value of the first scalar member.

     foreach($obj_list as $obj)
        $map[] = array($obj->some_var, $obj);
     sort($map); // sorts $map by the value of ->some_var
    

    I guess this still will be 10000000 times faster than usort

提交回复
热议问题