2

I have the following function which should return all the tournaments and corresponding rounds inside an array.

When I call the function inside the body using a print_r I get only one tournament and round returned, however there are multiple tournaments and rounds. It is like the loop exits after only one iteration

function getTournaments(){
    global $db;
        $sql = "SELECT tournament, weekNum 
                FROM schedule
                GROUP BY tournament";
        $stmnt = $db->prepare($sql);
        $stmnt->execute();
        $tournaments = $stmnt->fetchAll();

        $data = array();
        foreach($tournaments as $tournament){
                $data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);

        }//foreach
        return $data;
}//function

print_r(getTournaments());

Database dump

Here you can see the corresponding mysql statement run on the db

enter image description here

My output / Problem

As you can see on image below I only get one tournament and round returned when doing print_r, why am I not getting all tournaments and rounds returned inside the function array? Am I missing something here?

enter image description here

2
  • 2
    Instead of copying the array row by row just to rename a column, you could also use a column alias in your query SELECT tournament, weekNum as `round` and then return $stmnt->fetchAll(PDO::FETCH_ASSOC); Commented Feb 24, 2017 at 2:55
  • @PaulSpiegel great advise thank you will definitely start implementing mentioned suggestion, learning each day! Commented Feb 24, 2017 at 3:08

2 Answers 2

3

you over write $data in the loop you want to create new arrays (multidimensional):

$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
Sign up to request clarification or add additional context in comments.

1 Comment

So you are saying I only missed the [] on $data array...? Thank you
0

You should have used $data as an array :) Use this

 $data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);

instead of

$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);

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.