Reputation: 1399
I have this array, which is already sorted by '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
I wanted to be sorted by the value of 'games' while respecting the order of sorted 'name' if the value of 'games' are the same.
The result should look like this:
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
I've tried practically all sort functions and user-defined comparison function, but couldn't find the right one.
If it is possible, how can I approach it if I want 'games' DESC while maintaining the sorted 'name' ASC if the value of games are the same? Example:
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
Upvotes: 1
Views: 114
Reputation: 31641
There are other approaches using custom comparison functions, but the simplest approach is with array_multisort
.
First create arrays with the keys by which you want to sort your array. Then supply those arrays with the sorting parameters to 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.
Upvotes: 0
Reputation: 522342
usort($array, function ($a, $b) {
if ($a['games'] == $b['games']) {
return strcmp($a['name'], $b['name']);
} else {
return $a['games'] - $b['games'];
}
});
Upvotes: 2