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