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条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置