嵌套for循环导致重复条目

时间:2018-05-25 07:51:34

标签: php for-loop nested-loops

我遇到以下代码问题。我得到数据库中内容的重复条目。 我认为它与for循环有关,但我不知道如何纠正它。

SQL查询:

  public function getConfRoomList()
  {
      $arr = array();
      $statement = $this->conn->prepare("SELECT id, name, roomnbr, location, seats, utilities from moterom order by name ASC");
      $statement->bind_result($id, $name, $roomnbr, $location, $seats, $utilities);
      $statement->execute();
      while ($statement->fetch()) {
      $arr[] = [ "id" => $id, "name" => $name, "roomnbr" => $roomnbr, "location" => $location, "seats" => $seats, "utilities" => $utilities];
      }
      $statement->close();

      return $arr;
  }

public function joinDevRoom()
  {
     $arr = array();
     $statement = $this->conn->prepare("SELECT r.name,GROUP_CONCAT(u.device) FROM moterom r LEFT JOIN utilities u ON FIND_IN_SET(u.id,r.utilities)>0 GROUP BY r.id");
     $statement->bind_result($id, $utilities);
     $statement->execute();
     while ($statement->fetch()) {
       $utilities = str_replace(',','<br />',$utilities);
       $arr[] = [ "id" => $id, "utilities" => $utilities];
     }
     $statement->close();

     return $arr;
  }

    public function getDeviceList()
    {
          $arr = array();
          $statement = $this->conn->prepare("SELECT id, device, model, img, supplier from utilities order by device ASC");
          $statement->bind_result($id, $device, $model, $img, $supplier);
          $statement->execute();
          while ($statement->fetch()) {
            $arr[] = [ "id" => $id, "device" => $device, "model" => $model, "img" => $img, "supplier" => $supplier];
          }
          $statement->close();

          return $arr;
    }

内容:

<?php
 require_once("db.php");
 $arr = $conn->getConfRoomList();
 $join = $conn->joinDevRoom();
 $dev = $conn->getDeviceList();
?>

<div class="add_dev_header">Møterom</div>
<?php
 if (!empty($arr)) { ?>

<table border='1'>
    <tr>
        <th>Conference room</th>
        <th>Room number</th>
    <th>Location</th>
    <th>Number of seats</th>
    <th>Available utilities</th>
    <th>Edit</th>
    <th>Delete</th>
    </tr>
    <?php for( $i=0; $i < count($arr); $i++) {
    for( $u=0; $u < count($join); $u++) {
    print_r  ("<tr>
     <td>".$arr[$i]['name']."</td>
     <td>".$arr[$i]['roomnbr']."</td>
   <td>".$arr[$i]['location']."</td>
   <td>".$arr[$i]['seats']."</td>
   <td>".$join[$u]['utilities']."</td>
   <td><a href='?p=editconfroomv2&id=".$arr[$i]['id']."'>Edit</a></td>
   <td><a href='?p=deleteconfroomdb&id=".$arr[$i]['id']."' class='delete'>Delete</a></td>
     </tr>"); } } ?>
</table>

<?php } else {
  echo "<div id='db_empty'>Database is empty...<br>
  You can be the first to <a href='?p=addconfroom'>register a conference room</a>.</div>";
}
?>

我在数据库中有两个房间和一个实用程序,打印结果如下所示:

房间1 |房间号码1 |位置1 |座位23 |齿轮1 |编辑|删除
1号房间房间号码1 |位置1 |座位23 |齿轮1 |编辑|删除
2号房间2号房间|位置2 |座位6 |齿轮1 |编辑|删除
2号房间2号房间|位置2 |座位6 |齿轮1 |编辑|删除

0 个答案:

没有答案