0

I want to sort this two-dimensional array. The array represents a football club and each row is a player.

First I want to sort by "position". I have a search array which represents the sort order. So finally the positions should be sorted like this:

  1. Goal keeper
  2. 2nd position
  3. 3rd position

Second I want to sort by "number" for each position ascending.

Before sorting:

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

After sorting:

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

Data:

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 )
)

I tried something with uasort(), subval_sort() and so on ... but nothing worked.

Can you help me? Thanks!

Boann
  • 48,794
  • 16
  • 117
  • 146
zerox76
  • 19
  • 3

1 Answers1

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'];
});

You said you want the sort by 'number' to be ascending, but the sample output you've provided shows a descending sort. The above code does it in ascending order, but if you want to reverse it change $a['number'] - $b['number'] to $b['number'] - $a['number'];

Boann
  • 48,794
  • 16
  • 117
  • 146