0

我们试图在一个while循环中加入一个while。第一个 while 运行,结果显示在列表中 (139, 140, 141)。第二个列表只显示一个值(第一个部队)。结果如下:
139
1 部队
140
141

所以似乎第二个 while 只执行一次。我能做些什么来解决这个问题?

echo "<ul>";            
            while($user = $allUsersintroops->fetch_assoc())
            {

                if($user['userid'] == $_SESSION['userid'])
                {   
                    echo "<li>" . $user['troopid'].  " </li>";

                    while ($mytroops = $alltroops->fetch_assoc()) 
                    {
                        if($user['troopid'] == $mytroops['troopid'])
                        {
                            echo "<li>" . $mytroops['description'].  " </li>";
                        }
                    }
                }   
            }           
echo "</ul>";
4

1 回答 1

2

内部循环一旦fetch_assoc返回 false 就停止......但这表明所有找到的结果都结束了,并且它没有任何行可用于下一次迭代。

您应该将所有行从$alltroops一个数组中收集一次,然后对其进行迭代:

echo "<ul>";
$allTroopsList = array();
while ($mytroops = $alltroops->fetch_assoc()) {
  $allTroopsList []= $mytroops;
}
while($user = $allUsersintroops->fetch_assoc()) {
  if($user['userid'] == $_SESSION['userid']) {   
    echo "<li>" . $user['troopid'].  " </li>";

    foreach($allTroopsList as $mytroops) {
      if($user['troopid'] == $mytroops['troopid']) {
        echo "<li>" . $mytroops['description'].  " </li>";
      }
    }
  }   
}           
echo "</ul>";

Additionally, you should consider adding some filtering to your $allUsersintroops query, because you are only using a part of the the returned rows, which means the rest of the rows are sent from the DB to your code for no reason, wasting time and bandwidth.

于 2012-05-20T09:44:44.310 回答