doushan6161 2014-11-30 06:03
浏览 56
已采纳

嵌套'while'循环需要根据两个查询结果相等来返回信息

I am trying to display a set of offices ordered under a header that reflects the state in which the offices are located, like so:

State
 Office
 Office
 ...
State
 Office
 ...

I have beat my head against this one for a while. There is a single table 'offices' in the MySQL db which has each office's State listed under 'office_state'. Here's what I've come up with - but nothing is returned.

// 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'];

    }      
}

Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • dougang2749 2014-11-30 09:02
    关注

    try this

    <?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'];
            }
        }      
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源