PHP - 从数组创建锦标赛结果顺序

时间:2016-07-29 11:00:37

标签: php arrays foreach

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

$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];
    }

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

对于此数组,需要按降序排序

$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