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

后端 未结 4 1746
逝去的感伤
逝去的感伤 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 12:56

    maybe you can use the function "usort":

    class Genre {
        private $genre;
        private $count;
        ...
    
        public function __construct($g, $c)
        {
           $this->genre=g;
           $this->count=c;
        }
    
    
        public static function compare($a, $b)
        {
            if ($a->count < $b->count) return -1;
            else if($a->count == $b->count) return 0;
            else return 1;
        }
    
        ...
    }
    
    
    
    $genres= array(
      new Genre (1, 5),
      new Genre (2, 2),
      new Genre (3, 7)
    );
    
    usort($genres, array("Genre", "compare"));
    

    Regards Thomas

提交回复
热议问题