我有以下数组:
$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
array("firstname" => "James", "lastname" => "Brown", "age" => 31),
array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
);
以及以下排序功能:
function sortArray($data, $field)
{
if(!is_array($field)) $field = array($field);
usort($data, function($a, $b) use($field) {
$retval = 0;
foreach($field as $fieldname) {
if($retval == 0) $retval = strnatcmp($a[$fieldname],$b[$fieldname]);
}
return $retval;
});
return $data;
}
它工作得很好,但我想知道如何更改它以传递第三个参数,排序方向(ASC 或 DESC)。
谢谢!