我有一个多维数组,看起来像:
$arr=Array
(
[0] => Array
(
[0] => TEAM1
[1] => 3
[2] => 0
[3] => 422.47
[4] => 192.62
)
[1] => Array
(
[0] => TEAM2
[1] => 2
[2] => 1
[3] => 402.14
[4] => 210.70
)
[2] => Array
(
[0] => TEAM3
[1] => 3
[2] => 0
[3] => 376.79
[4] => 174.64
)
)
这5列分别是球队名、#胜、#负、#得、#负。
我如何排序$arr
列1 (# Wins)(降序),然后列2 (# Losses)(升序),然后列3 (# of Pts For)(降序)
我找到了一个使用array_multisort()
的解决方案
foreach ($arr as $key => $row) {
$wins[$key] = $row[1];
$losses[$key] = $row[2];
$ptsfor[$key] = $row[3];
}
array_multisort($wins, SORT_DESC, $losses, SORT_ASC, $ptsfor, SORT_DESC, $arr);
您可以简单地使用usort
函数,如
usort($arr, function($a,$b){
if($a[1] != $b[1])
return $b[1] - $a[1];
else if($a[2] != $b[2])
return $a[2] - $b[2];
else if($a[3] != $b[3])
return $b[3] - $a[3];
});
也可以像
一样使用usort($arr,function($a,$b){
$c = $b[1] - $a[1];
$c .= $a[2] - $b[2];
$c .= $b[3] - $a[3];
return $c;
});
你可以使用这个函数
function sort_array($array, $sortkey, $order)
{
if ($order == "DESC")
$or = "arsort";
else
$or = "asort";
foreach ($array as $key => $array_row)
{
$sort_values[$key] = $array_row[$sortkey];
}
$or($sort_values);
reset($sort_values);
while (list ($arr_key, $arr_val) = each($sort_values))
{
$sorted_arr[] = $array[$arr_key];
}
return $sorted_arr;
}