我想对这个二维数组进行排序。阵列代表一个足球俱乐部,每一排都是一名球员。
首先,我想按“位置”排序。我有一个代表排序顺序的搜索数组。所以最后的位置应该像这样排序:
其次我希望按每个位置升序的“数字”排序。
排序前:
number | name | position | age
-------+----------------+--------------+----
2 | Mario Goetze | 2nd position | 37
4 | Lukas Podolski | 2nd position | 24
1 | Marco Reuss | Goal keeper | 24
99 | Inge Schmidt | 3rd position | 23
排序后:
number | name | position | age
-------+----------------+--------------+----
1 | Marco Reuss | Goal keeper | 24
4 | Lukas Podolski | 2nd position | 24
2 | Mario Goetze | 2nd position | 37
99 | Inge Schmidt | 3rd position | 23
数据:
Array (
[83] => Array ( [number] => 2 [name] => Mario Goetze [position] => 2nd position [age] => 37 )
[96] => Array ( [number] => 4 [name] => Lukas Podolski [position] => 2nd position [age] => 24 )
[66] => Array ( [number] => 1 [name] => Marco Reuss [position] => Goal keeper [age] => 24 )
[359] => Array ( [number] => 99 [name] => Inge Schmidt [position] => 3rd position [age] => 23 )
)
我尝试使用uasort()
,subval_sort()
等等...但没有任何效果。
答案 0 :(得分:0)
$players = array(
83 => array ( 'number' => 2, 'name' => 'Mario Goetze', 'position' => '2nd position', 'age' => 37 ),
96 => array ( 'number' => 4, 'name' => 'Lukas Podolski', 'position' => '2nd position', 'age' => 24 ),
66 => array ( 'number' => 1, 'name' => 'Marco Reuss', 'position' => 'Goal keeper', 'age' => 24 ),
359 => array ( 'number' => 99, 'name' => 'Inge Schmidt', 'position' => '3rd position', 'age' => 23 )
);
usort($players, function($a, $b) {
if ($cmp = $a['position'] - $b['position']) return $cmp;
return $a['number'] - $b['number'];
});
你说你想按“数字”排序'升序,但您提供的样本输出显示降序排序。上面的代码是按升序排列的,但是如果您想将其反转,请将$a['number'] - $b['number']
更改为$b['number'] - $a['number']
;