Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

sorting

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 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;
    ...
}

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

like image 345
OZZIE Avatar asked Oct 05 '11 11:10

OZZIE


2 Answers

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();
like image 169
Tom Avatar answered Nov 10 '22 02:11

Tom


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

like image 45
Thomas Avatar answered Nov 10 '22 02:11

Thomas