繁体   English   中英

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

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

我如何使用php array_multisort对数组进行排序? 我找不到此类数组的任何示例。 我尝试了不同的方法,但是我不断收到错误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 )
);

我认为您的做法不正确。 array_multisort不是其他语言中的“排序依据”(即:按某些属性对数组元素进行排序),而是对第一个数组进行排序,并将该顺序回荡到所有后续数组。 并且在相等的情况下,它检查第二个数组的对应值,等等。

如果要按分数(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