如何排序数组并保留结果然后分配值

时间:2015-02-14 06:45:32

标签: php arrays sorting

我遇到了这个问题,我无法弄清楚如何给一个能获得相同位置的球队分数。例如。 3支队伍获得相似的百分比并且排在第3位,因此他们每个人都得到相似的分数。

  • 如果团队是第一名,他们会获得10分。
  • 如果球队获得第二名,他们将获得9分。
  • 如果球队获得第3名,则获得8分。
  • 如果球队获得第4名,他们将获得7分。
  • 如果球队获得第5名,他们将获得6分。
  • 如果球队排在第6位,他们将获得5分。
  • 如果球队排名第7,他们会获得4分。
  • 如果团队排名第8,他们会获得3分。

假设我有8支球队;

$team_aScore and $team_cScore = 98%; (first place)
$team_dScore, $team_eScore and $team_fScore = 96%; (3rd place)
$team_bScore = 94%; (5th place)
$team_gScore = 97%; (2nd place)
$team_hScore = 95%; (4th place)

我所做的是以最高分排名第一的球队。我知道团队a的id为1,团队b的id为2,等等......

  $array = array(1=>$team_aScore, 2=>$team_bScore, 3=>$team_cScore, 4=>$team_dScore, 5=>$team_eScore, 6=>$team_fScore, 7=>$team_gScore, 8=>$team_hScore);
arsort($array);

$x = 0;
foreach ($array as $key => $val) {
    $x++;

  if($x==1) {$givepts = 10;}
  if($x==2) {$givepts = 9;}
  if($x==3) {$givepts = 8;}
  if($x==4) {$givepts = 7;}
  if($x==5) {$givepts = 6;}
  if($x==6) {$givepts = 5;}
  if($x==7) {$givepts = 4;}
  if($x==8) {$givepts = 3;}

  $q = mysql_query("INSERT INTO teamScore(id,score) VALUES($x,$givepts)");

}

结果是这样,每个团队得到个人积分。

  • team_a = 10pts
  • team_c = 9pts
  • team_g = 8pts
  • team_d = 7pts
  • team_e = 6pts
  • team_f = 5pts
  • team_h = 4pts
  • team_b = 3pts

这不是我想要的。我想要实现的是这个

  • team_a = 10pts
  • team_c = 10pts
  • team_g = 9pts
  • team_d = 8pts
  • team_e = 8pts
  • team_f = 8pts
  • team_h = 7pts
  • team_b = 6pts

1 个答案:

答案 0 :(得分:0)

我设置的数据略有不同,因此更容易使用。我创建了一个team_score函数,为您的团队进行排序和分配。我将初始分配点值设置为10。然后,我将最后检查的分数存储在变量中,并根据它检查当前分数。如果它是相同的,我不会减少赋值点值。

<?php
// Data Setup
$team_tags = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
$team_scores = array(98, 98, 97, 96, 95, 95, 95, 94);
shuffle($team_scores);
$teams = array();
foreach ($team_tags as $tag) {
    $teams[$tag] = array_pop($team_scores);
}

// Sort and Score
$team_points = team_score($teams);
var_dump($team_points);
var_dump($teams);

function team_score($teams) {
    // Sort
    arsort($teams);
    // Max Points
    $points = 10;
    $last_score = false;
    // Assign Points
    $team_points = array();
    foreach ($teams as $tag => $score) {
        if ($last_score && $score < $last_score) {
            $points--;
        }
        $team_points[$tag] = $points;
        $last_score = $score;
    }
    return $team_points;
}