Consider the following print_r() of an array
Problem
There are 4 users who make predictions on the result of 3 matches in a tournament Calculate how many votes each team got.
PSEUDO
- Each match should have a total of 4 votes (since 4 users are voting)
- There are 3 outcomes HomeTeam Picked to win, AwayTeam Picked to win, Draw Picked
Loop over array keep track of number of votes in each match for Home Team, Away Team, Draw.
My Code to solve above problem
foreach($results as $result){ $homeTeam = $result['homeTeam']; $awayTeam = $result['awayTeam']; $draw = 'Draw'; $pickedTeam = $result['pickedTeam']; $nrVotes = $result['nrVotes']; $gameID = $result['gameID']; //CHECK IF NEW MATCH OR SAME MATCH ON ITERATION if($gameID !== $newGameID) { if ($homeTeam === $pickedTeam) { $homeVotes = $nrVotes; //homeTeam Got 0 Votes if (!isset($homeVotes)) { $homeVotes = 0; } } if ($awayTeam === $pickedTeam) { $awayVotes = $nrVotes; //AWAY Team Got 0 Votes if (!isset($awayVotes)) { $awayVotes = 0; } } if ($pickedTeam === $draw) { $drawVotes = $nrVotes; //Draw Got Zero Votes if (!isset($drawVotes)) { $drawVotes = 0; } } echo $homeTeam . 'Number Of Votes = ' . $homeVotes; echo '<br />'; echo $awayTeam . 'Number Of Votes = ' . $awayVotes; echo '<br />'; echo $draw . ' Number Of Votes = ' . $drawVotes; } //CHECK FOR NEW MATCH $newGameID = $result['gameID']; }//foreach
If been staring at the PC screen for a long time so Im not sure if it is a small logical error or if my approach is completely wrong, as im getting a weird output as can be seen on below screen shot:
Notice how the number of draw votes seem to get correctly calculated but not the rest....that is where my problem is, ive been stuck on if for hours
Additional Info DB table
Any help much appreciated.
UPDATE MYSQL QUERY
$sql ='SELECT picks.*, schedule.homeTeam, schedule.awayTeam, schedule.gameID, picks.team, COUNT(*) AS number_of_picks
FROM picks
JOIN schedule ON picks.gameID = schedule.gameID
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum
GROUP BY schedule.gameID, picks.team
ORDER BY schedule.gameID, picks.team';



if($gameID !== $newGameID), your code is only going to run for the first entry for each game in your array.