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

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

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

class Genre {
    private $genre;
    private $count;
    ...
}

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

您可以创建自定义排序方法并使用 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");

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

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();

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...