我有这个数组,已经按'name'ASC排序。
array
0 =>
array
'id' => '4'
'name' => 'iPad'
'games' => 5
1 =>
array
'id' => '5'
'name' => 'iPhone'
'games' => 5
2 =>
array
'id' => '6'
'name' => 'Nintendo DS'
'games' => 5
3 =>
array
'id' => '1'
'name' => 'Playstation 2'
'games' => 2
4 =>
array
'id' => '7'
'name' => 'Playstation 3'
'games' => 2
5 =>
array
'id' => '7'
'name' => 'Xbox 360'
'games' => 1
如果“游戏”的值相同,我希望按照“游戏”的值进行排序,同时尊重排序“名称”的顺序。
结果应如下所示:
array
0 =>
array
'id' => '7'
'name' => 'Xbox 360'
'games' => 1
1 =>
array
'id' => '1'
'name' => 'Playstation 2'
'games' => 2
2 =>
array
'id' => '7'
'name' => 'Playstation 3'
'games' => 2
3 =>
array
'id' => '4'
'name' => 'iPad'
'games' => 5
4 =>
array
'id' => '5'
'name' => 'iPhone'
'games' => 5
5 =>
array
'id' => '6'
'name' => 'iPod Touch'
'games' => 5
我几乎尝试了所有排序函数和用户定义的比较函数,但找不到合适的函数。
如果有可能的话,如果我想要“游戏”DESC,如果游戏的价值相同,那么在维持排序的“名称”ASC的情况下如何处理?例如:
array
0 =>
array
'id' => '6'
'name' => 'Nintendo DS'
'games' => 5
1 =>
array
'id' => '5'
'name' => 'iPhone'
'games' => 5
2 =>
array
'id' => '4'
'name' => 'iPad'
'games' => 5
3 =>
array
'id' => '1'
'name' => 'Playstation 2'
'games' => 2
4 =>
array
'id' => '7'
'name' => 'Playstation 3'
'games' => 2
5 =>
array
'id' => '7'
'name' => 'Xbox 360'
'games' => 1
答案 0 :(得分:2)
usort($array, function ($a, $b) {
if ($a['games'] == $b['games']) {
return strcmp($a['name'], $b['name']);
} else {
return $a['games'] - $b['games'];
}
});
答案 1 :(得分:0)
还有其他方法使用自定义比较函数,但最简单的方法是使用array_multisort
。
首先使用您希望对数组进行排序的键创建数组。然后将那些带有排序参数的数组提供给array_multisort
。
// first collect the sorting keys
// ensure that $thearray[$n]['key'] corresponds to $sortkey[$n]
$games = array();
$name = array();
foreach ($thearray as $item) {
$games = $item['games'];
$name = $item['name'];
}
// now sort
array_multisort($games, SORT_NUMERIC, SORT_ASC,
$name, SORT_STRING, SORT_ASC,
$thearray);
// $thearray is now sorted first by games, then by name.