我的首選array_multisort
PHP Manual我的答案在下面,你可以用參數指定排序順序。
除了靈活性,它應該比使用usort
更快,它存在的問題是它沒有真正爲排序順序進行參數化,所以也沒有重新發明輪子。
更舒適,把它包裝成一個函數指定鍵作爲字符串(Demo):
$sorted = $multisortByKey($array, 'conversions', SORT_DESC, 'label', SORT_ASC);
爲:
$array = array(
0 => array(
'label' => 'Germany',
'conversions' => 1,
),
1 => array(
'label' => 'United States',
'conversions' => 8,
),
2 => array(
'label' => 'France',
'conversions' => 1,
),
3 => array(
'label' => 'China',
'conversions' => 1,
),
4 => array(
'label' => 'Philippines',
'conversions' => 1,
),
5 => array(
'label' => 'Turkey',
'conversions' => 1,
),
);
$multisortByKey = function(array $a) {
$args = func_get_args();
$a = array_shift($args);
$extract = function($k) use($a) {return array_map(function($v) use($k) { return $v[$k]; }, $a); };
# NOTE: The following check/for-loop is not entirely correct
# as multiple sort parameters per entry are allowed. I leave this
# for practice.
$c = count($args);
if(!$c%2) throw new InvalidArgumentException('Parameter count mismatch');
for($i=0;$i<$c;$i+=2)
$args[$i] = $extract($args[$i]);
$args[] = &$a;
call_user_func_array('array_multisort', $args);
return $a;
};
$sorted = $multisortByKey($array, 'conversions', SORT_DESC, 'label', SORT_ASC);
var_dump($sorted);
上usort http://php.net外觀/manual/en/function.usort.php –