PHP在foreach中显示多维数组的结果 [英] PHP display results of multidimensional array in foreach
问题描述
对于经验丰富的程序员来说,这应该是一个简单的问题.
This should be a failry simple question for a more experienced programmer.
我正在开发一个基本的"Pickem应用程序",该应用程序允许用户预测谁让用户对他们认为会赢得体育比赛的人进行投票.很简单.
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.
对该函数执行 print_r()
可以完美地工作并返回正确的结果.结果以包含的多维数组的形式返回. gameID
, team
, number_of_votes
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
我的代码
$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函数返回数据
我的问题
我的问题是在我的foreach循环中显示/回显数据.我已经搜索过SO,大多数答案都指向一个简单的 foreach()
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
}
我的问题是,在尝试回显上面的变量时,我一直在获取NULL值.我对循环进行了许多调整,结果相同.
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...
推荐答案
如果您的 print_r()
数组是$ picks,则您的数组是多维数组,则需要再嵌套一个foreach()如下所示:
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
}
}
这篇关于PHP在foreach中显示多维数组的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!