Sort array by object property in PHP?

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

    I do not advice my solution in your example because it would be ugly (And I have not benchmarked it), but it works.... And depending of the need, it may help. :)

    class Person
    {
      public $age;
    
      function __construct($age)
      {
        $this->age = $age;
      }
    
      public function __toString()
      {
        return $this->age;
      }
    }
    
    $person1 = new Person(14);
    $person2 = new Person(5);
    
    $persons = array($person1, $person2);
    asort($persons);
    

提交回复
热议问题