如何使用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 )
);
答案 0 :(得分:1)
我认为你采取了错误的方式。 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 */
);