Sort Object in PHP

后端 未结 10 1362
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 01:51

What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.

$sortedObjectArary = sort($unsortedObjectArray, $Object-         


        
10条回答
  •  离开以前
    2020-11-29 02:29

    You can even build the sorting behavior into the class you're sorting, if you want that level of control

    class thingy
    {
        public $prop1;
        public $prop2;
    
        static $sortKey;
    
        public function __construct( $prop1, $prop2 )
        {
            $this->prop1 = $prop1;
            $this->prop2 = $prop2;
        }
    
        public static function sorter( $a, $b )
        {
            return strcasecmp( $a->{self::$sortKey}, $b->{self::$sortKey} );
        }
    
        public static function sortByProp( &$collection, $prop )
        {
            self::$sortKey = $prop;
            usort( $collection, array( __CLASS__, 'sorter' ) );
        }
    
    }
    
    $thingies = array(
            new thingy( 'red', 'blue' )
        ,   new thingy( 'apple', 'orange' )
        ,   new thingy( 'black', 'white' )
        ,   new thingy( 'democrat', 'republican' )
    );
    
    print_r( $thingies );
    
    thingy::sortByProp( $thingies, 'prop1' );
    
    print_r( $thingies );
    
    thingy::sortByProp( $thingies, 'prop2' );
    
    print_r( $thingies );
    

提交回复
热议问题