PHP:仅具有唯一对的嵌套循环

时间:2019-06-22 13:09:21

标签: php loops

我需要创建仅包含唯一对的数组,因此没有重复项。 问题在于,当彼此迭代时,由于某种原因,最后一对通常是重复的。

所以这是一个简单的例子:

<?php 

$teams = [
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
    ['id' => 4],
];

foreach ($teams as $team_a) {
    foreach ($teams as $team_b) {
        if ($team_a['id'] !== $team_b['id']) {
            $pairs[] = [$team_a['id'], $team_b['id']];
        }
    }
}

?>

返回类似这样的内容:

0: [1, 2]
1: [1, 3]
2: [1, 4]
3: [2, 1]
4: [2, 3]
5: [2, 4]
6: [3, 1]
7: [3, 2]
8: [3, 4]
...

因此您可以看到某些对是相同的,例如[1, 2][2, 1]。并且在半迭代之后,只有重复。

最有效的迭代方式是什么,并确保只有唯一的配对?

谢谢!

2 个答案:

答案 0 :(得分:2)

显然,当key(team_a)> key(team_b)时总是出现重复项

<?php 

$teams = [
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
    ['id' => 4],
];

foreach ($teams as $offset => $team_a) {
    foreach (array_slice($teams, $offset+1) as $team_b) {
        $pairs[] = [$team_a['id'], $team_b['id']];
    }
}

答案 1 :(得分:1)

您可以使用递归来执行此操作,而不是每个循环使用两次。

<?php

$teams = [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10];

getMatchup($teams);

function getMatchUp($teams, $matches = [], $start = 0) {
    // Check if the whole array has been checked
    if ($start == count($teams)) {
        return var_dump($matches);
    }
    // Check every option considering a certain start point
    for ($x = $start; $x < count($teams); $x++) {

        // As long the team is not the same, add to matches
        if ($start !== $x) {
            $matches[] = [$teams[$start] => $teams[$x]];
        }
    }
    // First team has been matched up, start matching the second team and so on..
    getMatchup($teams,$matches, $start + 1);
}

运行示例: http://sandbox.onlinephpfunctions.com/code/4277d966c4ceacdbe7024d14fb03fe05fd760471