[英]Loop only iterating once inside function
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 . 当我使用print_r
在身体内部调用该函数时,我仅返回一个锦标赛和回合,但是有多个锦标赛和回合 。 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 在这里,您可以看到在数据库上运行的相应mysql语句
My output / Problem 我的输出/问题
As you can see on image below I only get one tournament and round returned when doing print_r
, w hy am I not getting all tournaments and rounds returned inside the function array? 如您在下面的图片中看到的那样,在执行print_r
, 我只会得到一个锦标赛和回合 , 为什么不能在函数数组中返回所有锦标赛和回合? Am I missing something here? 我在这里想念什么吗?
您在要创建新数组(多维)的循环中过度写入$data
:
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
You should have used $data as an array :) Use this 您应该将$ data用作数组:)使用此
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
instead of 代替
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.