【问题标题】:PHP - create a tournament results order from arrayPHP - 从数组创建锦标赛结果顺序
【发布时间】:2016-07-29 11:00:36
【问题描述】:

假设我有以下总分数组,每个值都是锦标赛中玩家的分数。

$total_scores = array(350,200,150,150,75,75,75,0);

我需要创建一个表格,列出位置正确的球员,如果他们得分相同,列表应该反映这一点,即:

1.     Player 1     350
2.     Player 2     200
3.-4.  Player 3     150
3.-4.  Player 4     150
5.-7.  Player 5     75
5.-7.  Player 6     75
5.-7.  Player 7     75
8.     Player 8     0    

我试图做一些事情

foreach ($total_scores as $total_score) {
        $no_of_occurrences = array_count_values($total_scores)[$total_score];
    }

但无法弄清楚如何建立正确的位置编号。

【问题讨论】:

  • 3.-4.等等是什么意思?有必要吗?
  • 是他们在排名中的位置范围。玩家 3 和玩家 4 各有 150 分,因此并列排名第 3 和第 4 位。

标签: php arrays foreach


【解决方案1】:
<?php    
$scores = array(350,200,150,150,75,75,75,0);  //assuming you have sorted data otherwise you need to sort it first
    $count = array();
    $startIndex = array();
    $endIndex = array();
    $len = count($scores);
    for($i = 0; $i < $len; $i++){
        if(!isset($count[$scores[$i]])){
            $count[$scores[$i]] = 1;
            $startIndex[$scores[$i]] = $endIndex[$scores[$i]] = $i+1;
        }else{
            $count[$scores[$i]]++;
            $endIndex[$scores[$i]] = $i+1;          
        }
    }

    $i = 1;
    foreach($scores as $s){
        echo $startIndex[$s].'.';
        if($startIndex[$s] != $endIndex[$s]){
            echo '-'.$endIndex[$s].'.';
        }
        echo ' Player '.$i.' '.$s."\n";        //if newline not works try echoing <br>
        $i++;
    }

Working Demo

【讨论】:

  • 谢谢,效果很好!不过,一些解释会有所帮助...:-)
  • @user1049961 让我知道您不理解的部分..基本想法是我取一个值并检查它是否已经在我的计数数组中,如果不是,那么我增加计数并设置该值的起始和结束索引...如果它再次出现,我只需增加计数并更新结束索引:)
【解决方案2】:

对于这个Array需要降序排序

$total_scores = array(350, 200, 150, 150, 75, 75, 75, 0);
rsort($total_scores);
$no_of_occurrence = array_count_values($total_scores);
array_unshift($total_scores, ""); // For starting count from 1
unset($total_scores[0]); // For starting count from 1
$i = 1;
foreach ($total_scores as $key => $value)
{
    $position = array_keys($total_scores,$value);
    if($no_of_occurrence[$value] == 1)
    {
        echo "Position " . $i . " ";
        echo "Player " . $i . " " . $value . " ";
    }
    else
    {
        echo "Position " . $position[0] . " - " . end($position) . " ";
        echo "Player " . $i . " " . $value . " ";
    }
    $i++;
    echo "<br>";
}

以上代码的输出:

Position 1 Player 1 350 
Position 2 Player 2 200 
Position 3 - 4 Player 3 150 
Position 3 - 4 Player 4 150 
Position 5 - 7 Player 5 75 
Position 5 - 7 Player 6 75 
Position 5 - 7 Player 7 75 
Position 8 Player 8 0 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2017-09-01
    • 2011-01-12
    • 2021-12-14
    • 2017-05-21
    • 2020-10-08
    • 2011-01-12
    相关资源
    最近更新 更多