PHP: Sorting custom classes, using java-like Comparable?

后端 未结 4 1738
逝去的感伤
逝去的感伤 2021-02-06 12:37

How can I make my own custom class be sortable using sort() for example?

I\'ve been scanning the web to find any method of making a class Comparable like in Java but wi

4条回答
  •  孤城傲影
    2021-02-06 13:18

    __toString() works for me:

    class Genre
    {
        private $genre;
        private $count;
    
        public function __construct( $genre, $count = 0 )
        {
            $this->genre = $genre;
            $this->count = $count;
        }
    
        public function __toString()
        {
            return $this->count . ' ' . $this->genre;
        }    
    }
    
    $collection = array(
        new Genre( 'alternative', 3 ),
        new Genre( 'jazz', 2 ),
        new Genre( 'hiphop', 1 ),
        new Genre( 'heavy metal', 1 )
    );
    
    natsort( $collection );
    
    foreach( $collection as $genre )
    {
        echo $genre . "\n";
    }
    

    Produces:

    1 heavy metal
    1 hiphop
    2 jazz
    3 alternative
    

提交回复
热议问题