【问题标题】:I'm trying to make a match generator in Laravel. But every team appears twice in the output我正在尝试在 Laravel 中制作匹配生成器。但是每个团队在输出中出现两次
【发布时间】:2021-03-25 09:33:00
【问题描述】:

我正在 Laravel 中制作匹配生成器。我有一个名为 $matches 的数组。问题是,当我输出代码时,每个团队都打了两次。我使用的代码如下所示。

public function generateMatches($allContestants){
    $matches = [];
    
    for ($i=0; $i < count($allContestants) -1; $i++) { 
        $matches[] = [
            'team1' => $allContestants[$i]->id,
            'team2' => $allContestants[$i+1]->id
        ];
    }
    dd($matches);
}

这是我得到的输出:

array:3 [▼
  0 => array:2 [▼
    "team1" => "1"
    "team2" => "10"
  ]
  1 => array:2 [▼
    "team1" => "10"
    "team2" => "11"
  ]
  2 => array:2 [▼
    "team1" => "11"
    "team2" => "12"
  ]
]

如您所见,每场比赛的第二支球队是下一场比赛中使用的第一支球队。有谁知道如何解决这个问题?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果您想保持循环遍历数组的逻辑(而不是随机生成),您可以每次将 $i 增加 2 而不是 1。

    public function generateMatches($allContestants){
        $matches = [];
        
        for ($i=0; $i < count($allContestants) - 2; $i += 2) { 
            $matches[] = [
                'team1' => $allContestants[$i]->id,
                'team2' => $allContestants[$i+1]->id
            ];
        }
        dd($matches);
    }
    

    你现在唯一的问题是定义如果参赛者数量不均匀会发生什么。

    关于随机操作,你可以看看这个帖子:Using PHP, randomly pair up group of items, not pairing any with itself, no direct pairings

    【讨论】:

    • 解决了这个问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2021-10-22
    • 2018-08-12
    • 2020-12-21
    • 2021-07-11
    • 1970-01-01
    • 2023-02-01
    相关资源
    最近更新 更多