嵌套WHILE循环的问题

时间:2011-01-31 13:59:24

标签: php mysql

我遇到嵌套while循环的问题。我创建了这个函数来列出三个组,并且在每个组中我想要另一个循环来列出该组中最多四个成员:

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);
}

它列出了第一个精细循环(显示了三个组)但在每个组内部嵌套循环不起作用。我使用会员的ID作为示例内容。如果每个组中只有一个用户,并且说他们的成员ID为1,则输出:

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

因此,由于某种原因,嵌套循环继续运行得比它应该做的更多。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您应该在每次迭代时清除$mKeys数组:

// ...
while( (true == ($groups = mysql_fetch_assoc($allGroups))) && ($i < 3) ) {
    $mKeys = array();
    $gid = $groups['ThisID'];
    // ...

答案 1 :(得分:2)

$i++;

尝试:

unset($mKeys);