开发者

PHP array - Unique matching

Hey guys, i was wondering if you would help me a little with my PHP logic...

I would like to generate a league table based on the following data.. 开发者_StackOverflow中文版

  • A numeric array consisting of user_ids
  • a variable with a numeric value indicating how many unique games to be played between the pair..

I need to created an array to reflect each unique game..

player1 vs player2 
player1 vs player2
player1 vs player2

However i do not want dupes such as

player2 vs player 1 - This would be over the maximum game limit specified above as a variable even though the players are in a different order.

I am really struggling to wrap my head around the logic of this problem, so any help would be great..

Thanks,


Track the pairs, and their matches like this:

// $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 will contain all the unique matches.


i hope you ment it that way:

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

returns:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜