我是一名新手 PHP 程序员,在理解“嵌套”想法时遇到问题。当我运行以下代码时,它将显示表中从 $query3 (名字、姓氏等)列出的每个人,但是当它显示第二个和第三个 while 循环(分别使用 $query1 和 $query2)时,它只会执行此操作在第一个记录(列出的第一个员工)上,但在其他记录上都没有。我是否需要/如何为循环的每个实例重置 $employeeID 变量,或者我到底需要在哪里进行更改?
//pen some querying
$query1 = mysql_query("SELECT * FROM employees WHERE position='Supervisor' OR position='Area Manager' ORDER BY area, LastName, EmployeeNumber ");
$query2 = mysql_query("SELECT * FROM meetings WHERE meetingGroup='Management'");
//now write some wicked sick code that will change the world!
while($rows3 = mysql_fetch_array($query1)):
$firstname = $rows3['FirstName'];
$lasttname = $rows3['LastName'];
$area = $rows3['area'];
$employeeID = $rows3['EmployeeNumber'];
echo "<table border='1' align='center' width='75%'><tr><td width='25%'>$firstname $lasttname</td>";
while($rows1 = mysql_fetch_array($query2)):
$meetingID = $rows1['meetingID'];
$meetingName = $rows1['meetingName'];
echo "<td width='19%'>$meetingName</td>";
$query3 = mysql_query("SELECT * FROM meetingattendance WHERE employeeid='$employeeID' AND meetingid='$meetingID'");
while($rows2 = mysql_fetch_array($query3)):
$attendanceMark = $rows2['employeeattendance'];
if($attendanceMark = 1)
echo "<td><center><strong>X</strong></center></td>";
else
echo "No Record";
endwhile;
endwhile;
endwhile;
?>
最佳答案
让我们从嵌套循环开始。我将在这里给出一个示例,该示例将跳过查询以使这更容易理解。
<?php
$nested1 = array(10,11,12,13,14,15,16,17);
$nested2 = array(20,21,22,23,24,25,26,27);
$nested3 = array(30,31,32,33,34,35,36,37);
while ($rows3 = next($nested1)) {
echo "First Level: $rows3\n";
while ($rows1 = next($nested2)) {
echo " -- Second Level: $rows1\n";
while ($rows2 = next($nested3)) {
echo " -- -- Third Level: $rows2\n";
}
}
}
结果看起来有点像我期望你看到的
First Level: 10
-- Second Level: 20
-- -- Third Level: 30
-- -- Third Level: 31
-- -- Third Level: 32
-- -- Third Level: 33
-- -- Third Level: 34
-- -- Third Level: 35
-- -- Third Level: 36
-- -- Third Level: 37
-- Second Level: 21
-- Second Level: 22
-- Second Level: 23
-- Second Level: 24
-- Second Level: 25
-- Second Level: 26
-- Second Level: 27
First Level: 11
First Level: 12
First Level: 13
First Level: 14
First Level: 15
First Level: 16
First Level: 17
原因是我们在本例中使用 next ,它将内部指针移动到数组中的下一个元素。由于下次我们通过外循环时指针永远不会重置,我们将点击回显“First Level:$rows\n”;行,然后是下一个 while 循环。由于指针仍然位于数组的末尾,因此 next() 将失败并继续执行剩余的迭代。这与最内层循环 ($rows2) 相同。
我在这个示例中接下来使用的原因是,它的作用就像查询中使用的 mysql_fetch_array 函数一样,它将到达结果集的末尾,并且指针永远不会重置回开头。
话虽如此,您确实应该考虑在查询中使用 JOIN。具体从左连接开始,如下所示
SELECT * FROM employees as e
LEFT JOIN meetingattendance as m ON e.EmployeeNumber = m.employeeid
WHERE e.position='Supervisor' OR e.position='Area Manager'
ORDER BY e.area, e.LastName, e.EmployeeNumber
从这里开始,看看这是否能让您更接近您正在寻找的东西。
关于php - 嵌套 While 循环仅显示第一行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318360/