php - 获取将 PHP 数组一分为二的所有可能组合

标签 php arrays

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

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

$players = array("费德勒","德尔波特罗","纳达尔","穆雷");

输出数组应如下所示:

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

最佳答案

关于php - 获取将 PHP 数组一分为二的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297586/

相关文章:

javascript - 弹出数组元素,将其拆分并保存到不同的数组中

ios - 如何从返回的 plist 数组中获取字符串

php - 安装 PHP 期望扩展时出错

php - 从 SQL 中选择到数组中

php - 事件 div 的可能代码

c - 如何读取数组中int的随机数

c++ - 三维数组中的 C/C++ DWORD 到 BYTE 以及 BYTE 到 DWORD 转换

python - 有没有更好的方法通过将 'object' 替换为 mean 来将 'na' 类型数组转换为 numpy 数组?

javascript - 如何检查网站中页面的访问情况

php - Symfony 不能决定哪个类需要