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

后端 未结 4 1740
逝去的感伤
逝去的感伤 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:57

    You can create a custom sort method and use the http://www.php.net/manual/en/function.usort.php function to call it.

    Example:

    $Collection = array(..); // An array of Genre objects
    
    // Either you must make count a public variable, or create
    // an accessor function to access it
    function CollectionSort($a, $b)
    {
        if ($a->count == $b->count)
        {
            return 0;
        }
        return ($a->count < $b->count) ? -1 : 1;
    }
    
    usort($Collection, "CollectionSort");
    

    If you'd like to make a more generic collection system you could try something like this

    interface Sortable
    {
        public function GetSortField();
    }
    
    class Genre implements Sortable
    {
        private $genre;
        private $count;
    
        public function GetSortField()
        {
            return $count;
        }
    }
    
    class Collection
    {
        private $Collection = array();
    
        public function AddItem($Item)
        {
            $this->Collection[] = $Item;
        }
    
        public function GetItems()
        {
            return $this->Collection;
        }
    
        public function Sort()
        {
            usort($this->Collection, 'GenericCollectionSort');
        }
    }
    
    function GenericCollectionSort($a, $b)
    {
        if ($a->GetSortField() == $b->GetSortField())
        {
            return 0;
        }
        return ($a->GetSortField() < $b->GetSortField()) ? -1 : 1;
    }
    
    $Collection = new Collection();
    $Collection->AddItem(...); // Add as many Genre objects as you want
    $Collection->Sort();
    $SortedGenreArray = $Collection->GetItems();
    

提交回复
热议问题