嵌套'而#39;循环需要根据两个查询结果相等返回信息

时间:2014-11-30 06:03:08

标签: php mysql

我试图在一个标题下显示一组办公室,这些办公室反映了办公室所处的状态,如下所示:

State
 Office
 Office
 ...
State
 Office
 ...

我已经打了一会儿对抗这个。有一张桌子办公室'在MySQL数据库中,每个办公室的状态列在&office;状态'下。这就是我所想出的 - 但没有任何回报。

// Here I return a list of the distinct States:
$stateQuery = 'SELECT DISTINCT office_state AS state FROM offices';
$stateResult = mysql_query($stateQuery);

// Here I return each office's information:
$officeQuery = 'SELECT office_information, office_state FROM offices';
$officeResult = mysql_query($officeQuery);

// And here's where I'm stuck:
while ($rows = mysql_fetch_assoc($stateResult)) {

    // This returns the distinct States:
    echo $rows['state'];

    // Here is my effort at listing each office within the State:
    $rows1 = mysql_fetch_assoc($officeResult);
    if ($rows['state'] == $rows1['office_state']) {
      echo $rows1['office_information'];

    }      
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

试试这个

<?php
// Here I return a list of the distinct States:
$stateQuery = 'SELECT DISTINCT office_state AS state FROM offices';
$stateResult = mysql_query($stateQuery);

// Here I return each office's information:
$officeQuery = 'SELECT office_information, office_state FROM offices';
$officeResult = mysql_query($officeQuery);

// And here's where I'm stuck:
while ($rows = mysql_fetch_array($stateResult)) {

    // Here is my effort at listing each office within the State:
    while($rows1 = mysql_fetch_array($officeResult)){
        if ($rows['state'] == $rows1['office_state']) {
          echo $rows1['office_information'];
        }
    }      
}
?>