是否可以使用数组mid for loop?

时间:2014-05-08 05:50:04

标签: php arrays

所以这个功能的重点是根据玩家排名创建平衡的团队。我的原始代码工作得很好:

function playerCreate(){
global $teams, $players;
//find the average captain MMR
$averageTeams = averageteams();
sortTeams();
//Any captain above average add the lowest MMR player
for($i = 0; $i < count($teams);$i++){
  if ($teams[$i]['totalMMR'] > $averageTeams){
    addPlayer($i,0);
}
//Any captain below average MMR add the highest MMR player
else {
    addPlayer($i,count($players)-1);
}
}} 

然而,平衡问题是四个循环的一半,它开始将评分最高的球员添加到排名第四的球队。这是因为for循环按特定顺序进行,并且会在第10队之前添加第6队的队员,而我的排序功能将是评分最低的队伍。

有没有办法对mid for循环或其他方式进行排序以更好地平衡这些团队?

我创建了一个名为rSortTeams()的函数,它将团队从最高评级到最低评级,但是当我尝试将其称为中间循环时,它们都会混乱。

sortTeams功能:

function sortTeams(){
   global $teams;
   usort($teams, function($a, $b) {
       return $a['totalMMR'] - $b['totalMMR'];
   });
}
function rSortTeams(){
   global $teams;
   usort($teams, function($a, $b) {
     return $b['totalMMR'] - $a['totalMMR'];
   });
}

以下是三个数组:

$captains = array();
for ($i = 1; $i <= 40; $i++){
  $players[] = array('name' => 'Player ' . $i, 'MMR' => rand(2800,4200));
}
for ($i = 1; $i <= 10; $i++){
  $captains[] = array('name' => 'Captain ' . $i, 'MMR' => rand(3200,4200));
}
$teams = array();
//put captains on teams
for($i = 0;$i < count($captains); $i++){
$teams[] = array('name' => 'Team ' . ($i + 1), 'captain' => $captains[$i], 'players' => array(), 'totalMMR' => $captains[$i]['MMR']);
}

addPlayer函数:

function addPlayer($team,$newPlayer){
  global $teams, $players;
  $teams[$team]['players'][] = $players[$newPlayer];
  $teams[$team]['totalMMR'] += $players[$newPlayer]['MMR'];
  unset($players[$newPlayer]);
  $players = array_values($players);
}

1 个答案:

答案 0 :(得分:0)

我想我明白了。我将功能更改为:

function playerCreate(){
  global $teams, $players;
  //find the average captain MMR
  $averageTeams = averageteams();
  $belowAverage = 0;
  $aboveAverage = 0;
  sortTeams();
  for($i = 0; $i < count($teams);$i++){
    if ($teams[$i]['totalMMR'] > $averageTeams){
      $aboveAverage++;
    }
    else {
      $belowAverage++;
    }
  }
  for($y = 0; $y < $belowAverage; $y++){
    addPlayer($y,count($players)-1);
  }
  for($z = count($teams)-1;$z > count($teams) - 1 - $aboveAverage; $z--){
    addPlayer($z,0);    
  }
 }