2016-07-29 23 views
2

請考慮我擁有以下總分數組,其中每個值都是錦標賽中玩家的分數。PHP - 從數組中創建錦標賽結果訂單

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

但無法弄清楚如何建立正確的位置編號。需要

+0

'3-4.'等這是什麼意思?有必要嗎? –

+0

這是他們在排名中的位置範圍。玩家3和玩家4各有150分,因此在排名中分享第3名和第4名。 – Max

回答

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

+0

謝謝,效果很棒!有些解釋會有幫助,雖然... :-) – user1049961

+0

@ user1049961讓我知道哪一部分你不明白..基本想法是我拿一個值,並檢查它是否已經在我的計數陣列,如果它不是那麼我增加計數以及設置該值的開始和結束索引...如果它再次出現我只是增加計數和更新結束索引:) –

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