我有一系列玩家,每个玩家都有很多分数。
我可以使用自定义的usort函数按照点的顺序轻松地对数组进行排序。
但是当两个玩家拥有相同数量的积分时,我需要将它们排在列表中的相同获胜位置。
E.g。
在这种情况下,我需要的数据是
所以得分相等的球员被指定为相同的排名位置。
计算这些职位的最佳方法是什么?
谢谢!
答案 0 :(得分:1)
我认为以下代码可以按要求完成工作:
$scores = array('Nick'=>25,'Tom'=>18,'Chris'=>18,'Dave'=>16, 'James'=> 8,);
$scores_numbers = array_unique(array_values($scores));
$scores_counter = array_count_values($scores);
$pos = 1;
foreach($scores_numbers as $num) {
foreach($scores as $name=>$score) {
if($num == $score) {
if($scores_counter[$score] > 1) {
echo "$name - (joint) $pos<br />";
} else {
echo "$name - $pos<br />";
}
}
}
$pos++;
}
我已更新代码以避免重复输出。
答案 1 :(得分:1)
如果您要从数据库中检索玩家统计数据,那么下面的代码可用于对它们进行排名:
<?php
$players = [
['name' => 'Ash',
'point' => 0
],
['name' => 'Bob',
'point' => 10
],
['name' => 'Cane',
'point' => 0
],
['name' => 'Dory',
'point' => 6
],
['name' => 'Efat',
'point' => 6
],
];
usort($players, function($v1, $v2){
return $v2['point'] - $v1['point'];
});
$ranking = [];
$currentPosition = 0;
$heighestPoint = PHP_INT_MIN;
foreach($players as $player){
if($heighestPoint !== $player['point']){
$currentPosition++;
$heighestPoint = $player['point'];
}
$ranking[$currentPosition][] = $player;
}
print_r($ranking);
输出:
Array
(
[1] => Array
(
[0] => Array
(
[name] => Bob
[point] => 10
)
)
[2] => Array
(
[0] => Array
(
[name] => Dory
[point] => 6
)
[1] => Array
(
[name] => Efat
[point] => 6
)
)
[3] => Array
(
[0] => Array
(
[name] => Ash
[point] => 0
)
[1] => Array
(
[name] => Cane
[point] => 0
)
)
)
答案 2 :(得分:1)
这将通过额外修复为您提供所需内容:如果您在第2位有两名玩家,则下一位玩家应该在第4位。如果您不希望这个额外的修补程序移动$count++;
if语句。
$count = 0;
$position = 0;
$last_score = -1;
foreach ($players as $player)
{
$count++;
if ($last_score !== $player->score)
{
$position = $count;
}
$player->position = $position;
$last_score = $player->score;
}
答案 3 :(得分:1)
愿它有所帮助
/*Below array must be sorted */
$a1=array("Nick"=>25,"Tom"=>18,"Chris"=>18,"Dave"=>16,"James"=>8);
$makeUnique=array_unique($a1);
$makeUnique=array_values($makeUnique);
$pArr=array_map('setPosition',$a1);
print_r($pArr);
function setPosition($a){
Global $makeUnique;
return array_search($a,$makeUnique)+1;
}
OUT PUT
数组([Nick] =&gt; 1 [Tom] =&gt; 2 [Chris] =&gt; 2 [Dave] =&gt; 3 [James] =&gt; 4)
答案 4 :(得分:0)
我使用usort
对关联数组
$players = [["name" => "Nick" , "score" => 25] , ["name" => "Tom" , "score" => 18] , ["name" => "chris" , "score" => 18] , ["name" => "dave" , "score" => 16 ] , ["name" => "james" , "score" => 8]];
usort($players , function($a , $b) {return $b["score"] - $a["score"];} );
var_dump($players);
$lastScore = null;
$pos = 1;
foreach($players as $player)
{
if($lastScore != null && $lastScore == $player["score"])
echo $pos-1 . " - " . $player["name"] . '<br/>';
else
echo $pos++ . " - " . $player["name"] . '<br/>';
$lastScore = $player["score"];
}
中查看此代码