PHP数组 - 唯一匹配

时间:2011-05-30 15:12:20

标签: php arrays logic numeric

嘿伙计们,我想知道你是否会用我的PHP逻辑帮我一点......

我想基于以下数据生成一个联赛表。

  • 由user_ids
  • 组成的数字数组
  • 一个变量,其数值表示该对之间要播放的唯一游戏数量。

我需要创建一个数组来反映每个独特的游戏..

player1 vs player2 
player1 vs player2
player1 vs player2

但是我不想要像

这样的骗局

player2 vs player 1 -即使玩家的顺序不同,这也会超过上面指定的最大游戏限制。

我真的很想绕过这个问题的逻辑,所以任何帮助都会很棒..

谢谢,

2 个答案:

答案 0 :(得分:2)

跟踪对子及其匹配如下:

// $players - the players width ids
// $num_of_matches - max number of matches between 2 players

$match_counter = array();
$matches = array();
foreach ($players as $idA)
{
    foreach ($players as $idB)
    {
        if ($idA != $idB)
        {
            $match_id = $idA < $idB ? $idA."vs".$idB : $idB."vs".$idA;
            if (empty($match_counter[$match_id])) 
                $match_counter[$match_id] = 1
            elseif ($match_counter[$match_id] < $num_of_matches)
                $match_counter[$match_id] += 1;
            $match_id .= "_".$match_counter[$match_id];
            $matches[$match_id] = "player".$idA." vs player".$idB;
        }
    }
}

$ matches将包含所有唯一匹配。

答案 1 :(得分:1)

我希望你这样做:

$players = array(1, 2, 3);
$games = 3;

for($i=0; $i<$games; $i++){
    for($j=0; $j<(count($players)-1); $j++){
        for($k=1; $k<count($players); $k++){
            if($j != $k)
                echo 'player' . $players[$j] . ' - player' . $players[$k] . '<br />';
        }
    }
}

返回:

player1 - player2
player1 - player3
player2 - player3
player1 - player2
player1 - player3
player2 - player3
player1 - player2
player1 - player3
player2 - player3