Sort array by object property in PHP?

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

    For that specific scenario, you can sort it using the usort() function, where you define your own function to compare the items in the array.

    age = $age;
      }
    }
    
    function personSort( $a, $b ) {
        return $a->age == $b->age ? 0 : ( $a->age > $b->age ) ? 1 : -1;
    }
    
    $person1 = new Person(14);
    $person2 = new Person(5);
    $person3 = new Person(32);
    $person4 = new Person(150);
    $person5 = new Person(39);
    $people = array($person1, $person2, $person3, $person4, $person5);
    
    print_r( $people );
    
    usort( $people, 'personSort' );
    
    print_r( $people );
    

提交回复
热议问题