基本上,您要做的是使用一系列“短路”比较。考虑到上述标准,一个天真的例子可能看起来像这样(未经测试):
function mySort($a, $b) {
if ($a->name < $b->name) {
return -1;
}
if ($a->name > $b->name) {
return 1;
}
// If we get this far, then name is equal, so
// move on to checking type:
if ($a->type < $b->type) {
return -1;
}
if ($a->type > $b->type) {
return 1;
}
// If we get this far, then both name and type are equal,
// so move on to checking date:
if ($a->date < $b->date) {
return -1;
}
if ($a->date > $b->date) {
return 1;
}
// If we get this far, then all three criteria are equal,
// so for sorting purposes, these objects are considered equal.
return 0;
}
不过,正如我所说,这是一个幼稚的解决方案,而且非常不可扩展。我建议使用更强大的解决方案,其中您的排序不会硬编码到排序方法中。以这种方法为例(未经测试):
// These are the properties to sort by, and the sort directions.
// They use PHP's native SORT_ASC and SORT_DESC constants.
$this->_sorts = [
'name' => SORT_ASC,
'type' => SORT_ASC,
'date' => SORT_ASC
];
// Implemented as a class method this time.
protected function _mySort($a, $b) {
foreach ($this->_sorts as $property => $direction) {
if ($a->{$property} < $b->{$property}) {
return $direction === SORT_ASC ? -1 : 1;
}
if ($a->{$property} > $b->{$property}) {
return $direction === SORT_ASC ? 1 : -1;
}
}
return 0;
}
现在,添加或删除不同的排序字段或排序方向就像添加或修改数组元素一样简单。无需修改代码。