开发者

Problem with nested WHILE loops

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?


You should clear the $mKeys array on each iteration:

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


after

$i++;

try:

unset($mKeys);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜