PHP:使用类似Java的Comparable对自定义类进行排序?

OZZ*_*ZIE 5 php sorting

如何使用sort()使我自己的自定义类可以排序?

我一直在扫描网络,找到任何一种类似Java的类比较方法,但没有太多运气.我尝试实现__equals()但没有运气.我也试过__toString().我的班级看起来像这样:

class Genre {
    private $genre;
    private $count;
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想按顺序对它们进行排序,这是一个整数,按降序排列......($ genre是一个字符串)

Tom*_*Tom 11

您可以创建自定义排序方法并使用http://www.php.net/manual/en/function.usort.php函数来调用它.

例:

$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");
Run Code Online (Sandbox Code Playgroud)

如果你想制作一个更通用的收藏系统,你可以试试这样的东西

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();
Run Code Online (Sandbox Code Playgroud)