0

我是一名新手 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;
?>
4

1 回答 1

1

让我们从嵌套循环开始。我将在此处给出一个示例,该示例将跳过查询以使其更易于理解。

<?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 ,它将内部指针移动到数组中的下一个元素。由于下次我们通过外部循环时指针永远不会重置,我们将点击 echo "First Level: $rows\n"; 行,然后是下一个 while 循环。由于指针仍在数组的末尾,next() 将失败并继续迭代的其余部分。这与最内层循环 ($rows2) 相同。

我在此示例中使用 next 的原因是它的行为就像查询中使用的 mysql_fetch_array 函数一样,它将到达结果集的末尾,并且指针永远不会重置回开头。

话虽如此,您确实应该考虑在查询中使用 JOIN。具体从 Left 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

从那里开始,看看这是否能让你更接近你正在寻找的东西。

于 2012-11-10T03:57:05.443 回答