Sort array by object property in PHP?

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

    I just coded this. It should be faster than usort as it does not rely on numerous function calls.

    function sortByProp($array, $propName, $reverse = false)
    {
        $sorted = [];
    
        foreach ($array as $item)
        {
            $sorted[$item->$propName][] = $item;
        }
    
        if ($reverse) krsort($sorted); else ksort($sorted);
        $result = [];
    
        foreach ($sorted as $subArray) foreach ($subArray as $item)
        {
            $result[] = $item;
        }
    
        return $result;
    }
    

    Usage:

    $sorted = sortByProp($people, 'age');
    

    Oh, and it uses ksort but it works even if many $people are of the same $age.

提交回复
热议问题