简体   繁体   中英

php array_multisort(): Array sizes are inconsistent

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

I think you're taking it the wrong way. array_multisort is not what would be a "sort by" in other languages (ie: 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 */
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM