PHP:使用类似Java的Comparable对自定义类进行排序? [英] PHP: Sorting custom classes, using java-like Comparable?

查看:168
本文介绍了PHP:使用类似Java的Comparable对自定义类进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我一直在网上搜索以找到使类Comparable成为类的任何方法,就像Java中那样,但是运气不佳.我尝试实现__equals()但没有运气.我也尝试了__toString().我的课看起来像这样:

I've been scanning the web to find any method of making a class Comparable like in Java but without much luck. I tried implementing __equals() but without luck. I've also tried with __toString(). My class looks like this:

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

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

I want to sort them by count which is an Integer, in descending order... ($genre is a string)

推荐答案

您可以创建自定义排序方法并使用

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

示例:

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

这篇关于PHP:使用类似Java的Comparable对自定义类进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆