douhe4336 2011-01-31 13:59
浏览 378
已采纳

嵌套WHILE循环的问题

I've having trouble with nested while loops. I've created this function to list three groups and WITHIN each group I want another loop to list up to four members of that group:

function getBlockCode_MainBody() {
    global $oSysTemplate;
    $allGroups = db_res("SELECT g.*, g.id AS ThisID, COUNT(m.id_profile) AS members FROM bx_groups_main AS g LEFT JOIN bx_groups_fans AS m ON g.id = m.id_entry GROUP BY g.id HAVING members >= 1 ORDER BY RAND() LIMIT 3");
    $i = 0;
    while( (true == ($groups = mysql_fetch_assoc($allGroups))) && ($i < 3) ) {
       $gid = $groups['ThisID'];
       $members = db_res("SELECT * FROM bx_groups_fans WHERE id_entry = {$gid}");
       while( $member = mysql_fetch_assoc($members) ) {
          $gid = $member['id_profile'];
          $mKeys[] = array(
             'thumbnail' => $gid,
          );
       }
       $gKeys[] = array(
          'title' => $groups['title'],
          'gid'   => $groups['id'],
          'bx_repeat:members' => $mKeys,
       );
       $i++;
    }
    $aTemplateKeys = array(
      'bx_repeat:groups'  => $gKeys,
    );
    return $oSysTemplate -> parseHtmlByName('groups_main.html', $aTemplateKeys);
}

It's listing the first loop fine (three groups are shown) but inside each group the nested loop isn't working. I've used the member's ID for example content. If there's only one user in each group, and say their member ID is 1, it outputs:

GROUP 1 - 1 
GROUP 2 - 1 1 
GROUP 3 - 1 1 1

So, for some reason, the nested loop keeps on running more than it should do. Can anyone help?

  • 写回答

2条回答 默认 最新

  • dongyan2445 2011-01-31 14:02
    关注

    You should clear the $mKeys array on each iteration:

    // ...
    while( (true == ($groups = mysql_fetch_assoc($allGroups))) && ($i < 3) ) {
        $mKeys = array();
        $gid = $groups['ThisID'];
        // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 Python如何后台操作Vmwake虚拟机键鼠
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容