title: Football league - generate matches
body: <p>I'm currently making a football online manager game, and I'm stuck trying to generate the matches.</p>
  
  <p>This is my SQL structure:</p>
  
  <pre><code>id:     integer
  home:   integer (home team)
  away:   integer (away team)
  date:   integer
  league: integer
  </code></pre>
  
  <p>My leagues will contain many teams, so a team won't be able to compete against all of the other teams.</p>
  
  <p>My solution so far has been to loop across all possible match-ups, and then give it a unique date (based on a certain amount of given dates). However, that can't work now that I have too many teams in the leagues.</p>
  
  <p>Logic:</p>
  
  <ul>
  <li>Home and away cannot contain the same id.</li>
  <li>A match have a unique date if there can't be found a match which have the given date, and one of the teams competing.</li>
  <li>All teams must have the same amount of matches (to make it fair for all)</li>
  <li>Teams must have the same amount of home og away games.</li>
  </ul>
  
  <p>League:
  
  <li>The amount of teams in the league is uniform.
  <li>The whole season is generated at once.
  <li>The season last 1 week and has 28 specific dates within that week, which can be used as match dates.</p>
  
  <p><br>
  I don't have any code to show because the code I have has become irrelevant (because I'm looking for a different solution). I'm not looking for complete code, just guide me the way.</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <pre><code>foreach ($teams as $team_home) {
      foreach ($teams as $team_away) {
          if ($team_home === $team_away) continue;
  
          if (!isset($represented[$team_home->id]['home'])) $represented[$team_home->id]['home'] = 0;                 
          if (!isset($represented[$team_away->id]['away'])) $represented[$team_away->id]['away'] = 0;
  
          if ($represented[$team_away->id]['away'] == count($dates)/2) continue;
  
          $matches[] = array(
              'home' => $team_home->id,
              'away' => $team_away->id,
          );
  
          $represented[$team_home->id]['home']++;
          $represented[$team_away->id]['away']++;
  
          if ($represented[$team_home->id]['home'] == count($dates)/2) break;
      }
  }
  </code></pre>
  
  <p>The array represented keeps track of how many games the teams play as home and away. Please notice that a team maximum can have 50% of the dates given as home games.<br>
  <br>
  Example output:</p>
  
  <pre><code>Array
  (
      [1] => Array
          (
              [home] => 14
              [away] => 14
          )
  
      [2] => Array
          (
              [away] => 14
              [home] => 14
          )
  
      ....
  
  
      ....
  
      [25] => Array
          (
              [away] => 9
              [home] => 9
          )
  )
  </code></pre>
  
  <p>As you can see, the last teams which are looped doesn't play 14 home and away games as the others.</p>