Sort array by object property in PHP?

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

    Yes. If you implement spl ArrayObject in your person object, all the normal php array functions will work properly with it.

    0 讨论(0)
  • 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.

    <?php
    
    class Person {
      var $age;
      function __construct($age) {
        $this->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 );
    
    0 讨论(0)
  • 2020-12-04 12:54

    Try usort: http://www.php.net/manual/en/function.usort.php

    Example:

    <?php
    function cmp($obja, $objb)
    {
        $a = $obja->sortField;
        $b = $objb->sortField;
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array( /* your objects */ );
    
    usort($a, "cmp");
    
    ?>
    
    0 讨论(0)
提交回复
热议问题