Reputation: 5714
This should be a failry simple question for a more experienced programmer.
Im working on a basic "pickem app" which allows users to predict who lets users vote on who they believe will win a sports game. Simple enough.
I wrote the following function to display statistics for each match. I.E the function returns how many votes each team received.
Doing a print_r()
on the function it works perfectly and returns the correct results. The results are returned in the form of a multidimensional array containing. gameID
, team
, number_of_votes
My Code
$sql='SELECT gameID, team, COUNT(*) AS number_of_picks
FROM picks
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum
GROUP BY gameID, team
ORDER BY gameID, team';
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tournament', $tournament);
$stmnt->bindValue(':weekNum', $week);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
$result = array();
foreach ($stmnt->fetchAll() as $row) {
$result[$row['gameID']][] = $row;
}
return $result;
}
return false;
}
Print_R function return data
My Problem
My problem is displaying / echo'ing the data in my foreach loop. I have searched on SO and most answers points towards a simple foreach()
$picks = $calcStats('Tournament', Round);
foreach($picks as $pick){
echo $pick['gameID']; //gameID
echo $pick['team']; //Which Team Will Win
echo $pick['number_of_votes'] //How many votes did each team get
}
My problem is I keep on getting NULL values back when trying to echo variables above. I made a number of tweaks to the loop with same result.
What am I missing here? Any help / advice appreciated...
Upvotes: 0
Views: 412
Reputation: 2561
If your print_r()
array is $picks, then your array is a multidimensional array, you need one more nested foreach() like below:
<?php
$picks = $calcStats('Tournament', Round);
foreach($picks as $keyArr){
foreach($keyArr as $pick)
echo $pick['gameID']; //gameID
echo $pick['team']; //Which Team Will Win
echo $pick['number_of_picks'] //it should be this according to your print_r data
}
}
Upvotes: 1