how to output a standings table on the fly from a mysql table of football [soccer] results?

后端 未结 3 1824
天命终不由人
天命终不由人 2020-12-13 16:07

I have been trying to find something about this topic and I can\'t seem to find anything, there were a few questions on here but they didn\'t work for my particular project.

3条回答
  •  庸人自扰
    2020-12-13 16:17

    // connection stuff
    $sql = 'select * from matchesTable';
    $result = mysql_query($sql)
    
    $standings = array ();
    $standingTemplate = array ('matches' => 0, 'wins' => 0, 'draws' => 0, 'losses' => 0, 'goalsfor' => 0, 'goalsagainst' => 0, 'goalsdiff' => 0, 'points' => 0);
    
    while ($row = mysql_fetch_assoc($result)) 
    {
        handleMatch($row['hometeam'], $row['goalsfor'], $row['goalsagainst']);
        handleMatch($row['awayteam'], $row['goalsfor'], $row['goalsagainst']);
    
        print_r( usort(standings, 'comparePoints') );  // up to you to format the output as you like
    }
    
    function handleMatch($team, $goalsfor, $goalsagainst)
    {
        global $standings, $standingTemplate;
        if ($goalsfor > $goalsagainst) 
        {
            $points = 3;
            $win = 1;
            $draw = 0;
            $loss = 0;
        }
        elsif ($goalsfor == $goalsagainst) 
        {
            $points = 1;
            $win = 0;
            $draw = 1;
            $loss = 0;
        }
        else 
        {
            $points = 0
            $win = 0;
            $draw = 0;
            $loss = 1;
        }
    
        if ( empty($standings[$team]) )$standing = $standingTemplate;
        else $standing = $standings[$team];
    
        $standing['matches']++;
        $standing['wins'] += $win;
        $standing['draws'] += $draw;
        $standing['losses'] += $loss;
        $standing['goalsfor'] += $goalsfor;
        $standing['goalsagainst'] += $goalsagainst;
        $standing['goalsdiff'] += $goalsfor - $goalsagainst;
        $standing['points'] += $points;
    
        $standings[$team] = $standing;
    
    }
    
    function comparePoints($a, $b)
    {
        if ($a['points'] == $b['points']) 
        {
            if ($a['goalsdiff'] == $b['goalsdiff']) return 0;
            return ($a['goalsdiff'] < $b['goalsdiff']) ? 1 : -1 ;
        }       
        return ($a['points'] < $b['points']) ? 1 : -1 ;
    }
    

    NOTES: I didn't test it and all, might be little bug (some $ or ; missing).

提交回复
热议问题