Sort array by object property in PHP?

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

    I went with the following approach: created a function that takes an array of objects, then inside the function I create an associative array using the property as key for the array, then sort they array keys using ksort:

    class Person {
        var $age;
        function __construct($age) {
          $this->age = $age;
        }
    }
    
    function sortPerson($persons = Array()){
        foreach($persons as $person){
            $sorted[$person->age] = $person;
        }
        ksort($sorted);
        return array_values($sorted);
    }
    
    $person1 = new Person(14);
    $person2 = new Person(5);
    
    $persons = array($person1, $person2);
    $person = sortPerson($persons);
    
    echo $person[0]->age."\n".$person[1]->age;
    /* Output:
    5
    14
    */
    

提交回复
热议问题