PHP: Sorting custom classes, using java-like Comparable? -
how can make own custom class sortable using sort() example?
i've been scanning web find method of making class comparable in java without luck. tried implementing __equals() without luck. i've tried __tostring(). class looks this:
class genre { private $genre; private $count; ... }
i want sort them count integer, in descending order... ($genre string)
you can create custom sort method , use http://www.php.net/manual/en/function.usort.php function call it.
example:
$collection = array(..); // array of genre objects // either must make count public variable, or create // accessor function access function collectionsort($a, $b) { if ($a->count == $b->count) { return 0; } return ($a->count < $b->count) ? -1 : 1; } usort($collection, "collectionsort");
if you'd make more generic collection system try 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 many genre objects want $collection->sort(); $sortedgenrearray = $collection->getitems();
Comments
Post a Comment