2

OK, so here's the deal: I'm trying to sort teams based on the following criteria (in order):

  1. overall record
  2. division record
  3. head-to-head results
  4. points

For items 1, 2, and 4, I can simply pull the data from an SQL database. So when I iterate through the SQL results, I can create the following array:

arr[$row['team_id']] => array('overall_wins'  => $row['wins'],
                              'division_wins' => $row['div_wins'],
                              'points'        => $row['pts']);

All good so far. The issue is when two or more teams have equal overall wins and division wins. In that case, I need to be able to use their head-to-head record to break the tie.

So my thought was to iterate through the above array and use temp variables to check if the current overall_wins and division_wins equal the previous team's values, and then "do something"...use head-to-head record to break the tie.

Now, I can get the head-to-head record between two teams using SQL again, so that's not the problem, but my question is:

How do I resort my array for display using the head-to-head record to break a tie between two teams?

Let's use the following example:

  team_id     overall_wins     division_wins
------------------------------------------
  B           6                6
  A           7                7
  E           6                5
  C           6                6
  G           10               9
  D           4                3
  F           2                0

This would at first pass be resorted as:

  team_id     overall_wins     division_wins
------------------------------------------
  G           10               9
  A           7                7
  B           6                6
  C           6                6
  E           6                5
  D           4                3
  F           2                0

...but let's say Team C beat Team B head-to-head. In that case, teams B and C need to be swapped in the above order.

I'm not sure how to do this within the confines of PHP arrays alone, without going full-out crazy with entire temporary arrays and whatnot.

Thoughts? Thanks.

4

1 回答 1

1

您可以使用 usort

  function compareTeams ($a, $b){
            if ($a["overall_wins"] == $b["overall_wins"]){
                if ($a["division_wins"] == $b["division_wins"]){
                   if ($a["head_to_head"] == $b["head_to_head"]){
                      return 0;
                   } else {
                      return $a["head_to_head"] == $b["head_to_head"];
                   }
                } else {
                   return $a["division_wins"] - $b["division_wins"];
                }
            } else {
                return $a["overall_wins"] - $b["overall_wins"];
            }
  }

  usort($arr, "compareTeams");

$arr 现在将根据您的需要进行排序

于 2013-07-15T21:23:21.050 回答