douye8500
douye8500
2017-02-24 02:37
浏览 146
已采纳

循环只在函数内迭代一次

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

图片转代码服务由CSDN问答提供 功能建议

我有以下功能,应该返回所有锦标赛和相应的回合 在数组内部。

当我使用 print_r 调用体内的函数时,我得到只有一个锦标赛 返回圆形,但有多个锦标赛和轮次就像循环仅在一次迭代后退出

  function getTournaments(){
 global $ db; 
 $ sql =“SELECT tournament  ,weekNum 
 FROM schedule 
 GROUP BY锦标赛“; 
 $ stmnt = $ db-> prepare($ sql); 
 $ stmnt-> execute(); 
 $ tournaments = $ stmnt->  fetchAll(); 
 
 $ data = array(); 
 foreach($ tournaments as $ tournament){
 $ data = array('tournament'=> $ tournament ['tournament'],'round'  => $ tournament ['weekNum']); 
 
} // foreach 
返回$ data; 
} // function 
 
print_r(getTournaments()); 
   
 
 

数据库转储

在这里您可以看到在db上运行的相应mysql语句 < p>

我的输出/问题

尽可能 在 print_r 时,我只得到一个锦标赛和回合,w 我是不是在函数数组中返回所有锦标赛和回合? 我在这里遗漏了什么吗?

< img src =“https://i.stack.imgur.com/R2Te7.png”alt =“在此输入图像说明”>

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doulu1914
    doulu1914 2017-02-24 02:39
    已采纳

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

    $data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
    
    点赞 评论
  • douxiezha9319
    douxiezha9319 2017-02-24 04:03

    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']);
    
    点赞 评论

相关推荐