简体   繁体   English

php array_multisort():数组大小不一致

[英]php array_multisort(): Array sizes are inconsistent

How can I use the php array_multisort to sort arrays like this? 我如何使用php array_multisort对数组进行排序? 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_multisort():数组大小不一致。

$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. array_multisort不是其他语言中的“排序依据”(即:按某些属性对数组元素进行排序),而是对第一个数组进行排序,并将该顺序回荡到所有后续数组。 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: 如果要按分数(desc),按游戏方式,按索引(然后按名称)来排序示例,则应永远不会发生这种情况,因为索引是唯一的,所以应该这样做:

$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 */
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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