1

How can I use the php array_multisort to sort arrays like this? I can't find any examples with this type of arrays. I have tried different avenues but I keep getting the error array_multisort(): Array sizes are inconsistent.

$array= Array (
    "Arnold" => Array ( "index" => 2, "games_played" => 1, "score" => 5 ),
    "Chris"  => Array ( "index" => 1, "games_played" => 1, "score" => 5 ),
    "Mike"   => Array ( "index" => 0, "games_played" => 2, "score" => 5 )
);
1
  • improved format Commented Mar 6, 2018 at 6:38

1 Answer 1

2

I think you're taking it the wrong way. array_multisort is not what would be a "sort by" in other languages (i.e: sort array elements by some properties), instead it sorts the first array, and reverberate that order to all following arrays. And in case of equality it checks the corresponding values of the second arrays, etc...

If you want to order your example by score (desc), then by game played, then by index (and then by name, but this should never happen since indexes are uniques) you should do:

$array= Array (
    "Arnold" => Array ( "index" => 2, "games_played" => 1, "score" => 5 ),
    "Chris" => Array ( "index" => 1, "games_played" => 1, "score" => 5 ),
    "Mike" => Array ( "index" => 0, "games_played" => 2, "score" => 5 )
);
$names = [];
$indexes = [];
$games_played = [];
$scores = [];
foreach ($array as $name => $player) {
    $names[] = $name;
    $indexes[] = $player['index'];
    $games_played[] = $player['games_played'];
    $scores[] = $player['score'];
}
array_multisort(
    $scores, SORT_DESC,
    $games_played,
    $indexes,
    $names,
    $array /* This line will sort the initial array as well */
);
Sign up to request clarification or add additional context in comments.

1 Comment

Note: There is actually a similar example in the manual here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.