获取PHP阵列分为两部分的所有可能组合

时间:2013-03-08 15:33:31

标签: php arrays

我正致力于生成运动队的代码。我有一个包含玩家列表的数组,并希望在所有可能的团队组合中存储另一个数组。

为了简单起见,让我们想象一场网球比赛,你将有4名球员分成两队。

$players = array("Federer","Del Potro","Nadal","Murray");

输出数组应如下所示:

$combinations[0][0] = "Federer","Del Potro";
$combinations[0][1] = "Nadal","Murray";

$combinations[1][0] = "Federer","Nadal";
$combinations[1][1] = "Del Potro","Murray";

$combinations[2][0] = "Del Potro","Nadal";
$combinations[2][1] = "Federer","Murray"; .. and so forth..

任何帮助?

提前致谢!

/// - 编辑

这是我到目前为止的代码。所有玩家也都有分数,我将此分数存储起来供以后使用。它并不重要。我想我已经有了它的工作,但我不确定这段代码是否能获得所有可能的组合。我做的是循环“玩家计数”次并开始建立团队,在团队建立之后,我将列表的第二个玩家移动到阵列的底部并再次循环。

 //-- Get the Max Players and the Array of Player Names
    $max_players = count($players)/2;
    $p = array_keys($players);

    for($i=0;$i<=(count($p));$i++){
        $tmp = array();
        $t=0;

        //-- Loop and start placing players into a team. When the max is reached, start placing on the other team.
        foreach($p as $player) {
            //-- Store player on Team
            $tmp[$t][] = $player;
            if(count($tmp[$t])==$max_players) {
                $t++;
            }
        }
        //-- Get the second player and move it to the bottom of the list.
        $second = $p[1];
        unset($p[1]);
        $p[] = $second;
        $p = array_values($p);

        //-- Loop thru teams and add the score of each player
        foreach($tmp as $key=>$eq) {
            $score = 0 ;
            foreach($eq as $jug) {
                //-- Add Score for each player
                $score +=  floatval($players[$jug]["score"]);
            }
            //-- Store the sum of scores of all players in team
            $tmp[$key]["score"] = $score;
        }
        //-- Store the Difference between team scores in this "team set"
        $tmp["diff"] = abs(round($tmp[0]["score"]-$tmp[1]["score"],2));
        $teams[] = $tmp;
    }

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

$ player_combination = []; $ match_combination = [];

  $players = array("Federer","Del Potro","Nadal","Murray");
  for($i = 0; $i< count($players);$i++){
      for($j=$i+1;$j<count($players);$j++){
        $player_combination[] = [$players[$i],$players[$j]]; 
       }
  }

  for($i = 0; $i< count($player_combination);$i++){
      for($j=$i+1;$j<count($player_combination);$j++){
        if(($player_combination[$i][0] !== $player_combination[$j][0]) &&  ($player_combination[$i][0] !== $player_combination[$j][1])&& ($player_combination[$i][1] !== $player_combination[$j][0]) && ($player_combination[$i][1] !== $player_combination[$j][1]))
        $match_combination[] = [$player_combination[$i],$player_combination[$j]]; 
       }
  }

我的网站是9amobile.com