如何使用sort()使我自己的自定义类可以排序?
我一直在扫描网络,找到任何一种类似Java的类比较方法,但没有太多运气.我尝试实现__equals()但没有运气.我也试过__toString().我的班级看起来像这样:
class Genre { private $genre; private $count; ... }
您可以创建自定义排序方法并使用
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();