0

Consider the following print_r() of an array

enter image description here

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:

Code Output enter image description here

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

enter image description here

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';
15
  • 2
    Again a picture of an array output. Stop posting text as pictures! Commented Feb 6, 2018 at 14:39
  • Out of curiosity - is this homework? Commented Feb 6, 2018 at 14:41
  • 1
    Your problem is this: if($gameID !== $newGameID), your code is only going to run for the first entry for each game in your array. Commented Feb 6, 2018 at 14:42
  • @andres so what is best practice...copy pasting the output? I simply feel its helpful to know the content of the array if I shouldn't post it as a picture I do apologize and did not know. Commented Feb 6, 2018 at 14:43
  • 1
    @Andreas I honestly didnt see that comment and did not know -- this is literally the first time Ive had someone complain about a screenshot. But thank you I'll keep it in mind for the future (P.S friendliness cost nothing smile pal) You think im purposelessly gonna post something that is viewed as bad practice. I take a great amount of time / effort to format any question I ask as good as I can, I just never knew about images...so once again humble apologies. Commented Feb 6, 2018 at 15:12

2 Answers 2

3

You have some issues in your code. First of all, the logical mistake you made lies here:

if($gameID !== $newGameID)

The if block will only be executed when the game ID changes, which of course only happens for the first entry for every game ID. That's why only the draw votes are correct.

Then there are some variables that you have never declared (e.g. $newGameID). This will yield a notice and is bad (even if you don't see it because display_errors is probably set to 0).

Furthermore, all your isset()s like here:

$homeVotes = $nrVotes;
if (!isset($homeVotes)) {

are pretty useless as you're declaring the variable right before, so !isset() will always evaluate to false.

I'd personally go for an array in this situation and do something like this:

$arr = array();
$currentGameId = -1;
foreach($results as $result) {
    $gameId = $result['gameID'];
    $homeTeam = $result['homeTeam'];
    $awayTeam = $result['awayTeam'];
    $pickedTeam = $result['pickedTeam'];
    $nrVotes = $result['nrVotes'];

    // initialize new subarray if game id changes
    if ($gameId != $currentGameId) {
        $arr[$gameId]['homeVotes'] = 0;
        $arr[$gameId]['awayVotes'] = 0;
        $arr[$gameId]['drawVotes'] = 0;

        // remember current game id
        $currentGameId = $gameId;
    }

    // add votes
    if ($pickedTeam == $homeTeam) {
        $arr[$gameId]['homeVotes'] += $nrVotes;
    } elseif ($pickedTeam == $awayTeam) {
        $arr[$gameId]['awayVotes'] += $nrVotes;        
    } else {
        $arr[$gameId]['drawVotes'] += $nrVotes;
    }
}

This will give you an array with the game IDs as index like this:

Array
(
    [127] => Array
        (
            [homeVotes] => 2
            [awayVotes] => 0
            [drawVotes] => 2
        )

    [128] => Array
        (
            [homeVotes] => 2
            [awayVotes] => 1
            [drawVotes] => 1
        )

)
Sign up to request clarification or add additional context in comments.

Comments

2

As billyonecan mentionned, your problem is

if($gameID !== $newGameID)

If you look at your array data, you'll notice that $results[0] is the first occurence of match 127 and it gives the amount of draw votes. Your if statement will make $results[1] and $results[2] be ignored. The same thing happens with match 128 and so on.

The way around this is to declare your variables first, and every time you change game number, you echo your variables and then reset them (don't forget to use the information contained in this line or you'll be missing a value);

Your code would look something like this:

<?php
function output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes){
    echo $homeTeam . ' Number Of Votes = ' . $homeVotes;
    echo '<br />';
    echo $awayTeam . ' Number Of Votes = ' . $awayVotes;
    echo '<br />';
    echo $draw . ' Number Of Votes = ' . $drawVotes;
    echo '<br />';
}

$results = array(
    0 => array('gameID' => '127','homeTeam' => 'Wales','awayTeam' => 'Scotland','pickedTeam' => 'Draw','nrVotes' => '3'),
    1 => array('gameID' => '127','homeTeam' => 'Wales','awayTeam' => 'Scotland','pickedTeam' => 'Wales','nrVotes' => '1'),
    2 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'Draw','nrVotes' => '1'),
    3 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'France','nrVotes' => '2'),
    4 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'Ireland','nrVotes' => '1')
);

$homeVotes = 0;
$awayVotes = 0;
$drawVotes = 0;
$newGameID = $results[0]['gameID'];

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) {
        // New match, output and reset
        output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes);
        $homeVotes = 0;
        $awayVotes = 0;
        $drawVotes = 0;

        if ($homeTeam === $pickedTeam) {
            $homeVotes = $nrVotes;
            //homeTeam Got 0 Vote
            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;
            }
        }

    }

    else {
        // The same match

        if ($homeTeam === $pickedTeam) {
            $homeVotes = $nrVotes;
            //homeTeam Got 0 Vote
            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;
            }
        }
    }
    //CHECK FOR NEW MATCH
    $newGameID = $result['gameID'];
   }//foreach

   //This line outputs the last match which would not be output otherwise.
   output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes);
?>

The if statements that are used to update the values should be put into a function in order to avoid replicate code. Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.