我在使用嵌套 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);
}
它列出了第一个循环(显示了三个组),但在每个组中,嵌套循环不起作用。我使用成员(member)的 ID 作为示例内容。如果每个组只有一个用户,且成员ID为1,则输出:
GROUP 1 - 1
GROUP 2 - 1 1
GROUP 3 - 1 1 1
因此,出于某种原因,嵌套循环继续运行超过它应该运行的时间。谁能帮忙?
您应该在每次迭代时清除 $mKeys
数组:
// ...
while( (true == ($groups = mysql_fetch_assoc($allGroups))) && ($i < 3) ) {
$mKeys = array();
$gid = $groups['ThisID'];
// ...
我是一名优秀的程序员,十分优秀!