PHP-对数组中的每个组合进行计算

时间:2018-09-25 20:24:31

标签: php arrays loops foreach

我在一个有比赛的团队中使用这个数组,现在我想为即将发生的每场比赛做一些计算。

Array
(
    [Team1] => Array
        (
            [totalHomeGoals] => 48
            [totalHomeAgainstGoals] => 12
            [totalAwayGoals] => 31
            [totalAwayAgainstGoals] => 11
        )

    [Team2] => Array
        (
            [totalHomeGoals] => 31
            [totalHomeAgainstGoals] => 25
            [totalAwayGoals] => 25
            [totalAwayAgainstGoals] => 27
        )

    [Team3] => Array
        (
            [totalHomeGoals] => 22
            [totalHomeAgainstGoals] => 21
            [totalAwayGoals] => 15
            [totalAwayAgainstGoals] => 38
        )
)

所以现在我想为每个可能的匹配进行计算。为了简单起见,假设我要将AwayGoals添加到Homegoals中,如下所示:

Team1 vs Team2 -> 48 + 25  
Team2 vs Team1 -> 31 + 31  
Team1 vs Team3 -> 48 + 15  
Team3 vs Team1 -> 22 + 31  
Team2 vs Team3 -> 31 + 15  


对于所有12种可能的比赛,等等

我应该朝着什么方向完成这项工作?

1 个答案:

答案 0 :(得分:1)

好的,这是我的建议。

首先,我修复了您的阵列。

$teams = Array
(
    'Team1' => Array
    (
        'totalHomeGoals'        => 48,
        'totalHomeAgainstGoals' => 12,
        'totalAwayGoals'        => 31,
        'totalAwayAgainstGoals' => 11
    ),
    'Team2' => Array
    (
        'totalHomeGoals'        => 31,
        'totalHomeAgainstGoals' => 25,
        'totalAwayGoals'        => 25,
        'totalAwayAgainstGoals' => 27
    ),
    'Team3' => Array
    (
        'totalHomeGoals'        => 22,
        'totalHomeAgainstGoals' => 21,
        'totalAwayGoals'        => 15,
        'totalAwayAgainstGoals' => 38,
    )
);

然后,我创建了一个函数,该函数将提供唯一的团队结果而不是。代码如下所示。

function showResult($i, $j, $param1, $param2, $teams, $teamKeys) {
    echo $teamKeys[$i] . ' vs ' . $teamKeys[$j] . ' -> ' . $teams[$teamKeys[$i]][$param1] . ' + ' . $teams[$teamKeys[$j]][$param2] . '<br/>';
}

function getAllResult($teams, $param1, $param2, $unique=true) {
    $teamKeys = array_keys($teams);
    for ($i = 0; $i < count($teams); $i++) {
        if(!$unique) {
            for ($j = 0; $j < count($teams); $j++) {
                showResult($i, $j, $param1, $param2, $teams, $teamKeys);
            }
        } else {
            for ($j = $i + 1; $j < count($teams); $j++) {
                showResult($i, $j, $param1, $param2, $teams, $teamKeys);
            }
        }
    }
}

如果要重复概率,例如Team1 VS Team2和Team2 VS Team1,这是它的工作原理。

getAllResult($teams, 'totalHomeGoals', 'totalAwayGoals', false);

输出:

Team1 vs Team1 -> 48 + 31
Team1 vs Team2 -> 48 + 25
Team1 vs Team3 -> 48 + 15
Team2 vs Team1 -> 31 + 31
Team2 vs Team2 -> 31 + 25
Team2 vs Team3 -> 31 + 15
Team3 vs Team1 -> 22 + 31
Team3 vs Team2 -> 22 + 25
Team3 vs Team3 -> 22 + 15

如果您只想拥有唯一的概率,这就是它的工作原理。

getAllResult($teams, 'totalHomeGoals', 'totalAwayGoals');

输出:

Team1 vs Team2 -> 48 + 25
Team1 vs Team3 -> 48 + 15
Team2 vs Team3 -> 31 + 15

然后,您可以根据自己的喜好更改属性。

让我知道您是否有任何疑问