Sort array by object property in PHP?

前端 未结 15 901
萌比男神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:51

    Here’s a stable Radix Sort implementation for values 0...256:

    function radixsort(&$a)
    {
        $n = count($a);
        $partition = array();
        for ($slot = 0; $slot < 256; ++$slot) {
            $partition[] = array();
        }
        for ($i = 0; $i < $n; ++$i) {
            $partition[$a[$i]->age & 0xFF][] = &$a[$i];
        } 
        $i = 0;
        for ($slot = 0; $slot < 256; ++$slot) {
            for ($j = 0, $n = count($partition[$slot]); $j < $n; ++$j) {
                $a[$i++] = &$partition[$slot][$j];
            }
        }
    }
    

    This costs only O(n) since Radix Sort is a non-comparing sorting algorithm.

提交回复
热议问题