У меня есть две таблицы, rooms
и utilities
.В таблице с именем rooms
есть столбец, который также называется utilities
.В этом столбце хранятся разделенные запятыми числа, ссылающиеся на идентификаторы из таблицы utilities
.
. Как разделить (разнести?) Значения из столбца utilities
и сопоставить их с таблицей utilities
, распечатавзначения, которые имеют совпадающие идентификаторы в качестве разделенных значений?
Пример:
Таблица: комнаты
| --------------- | --------------- | ----------------- |
| ID | Имя | Утилиты |
| --------------- | ---------------- | ----------------- |
|1 |Room1 |1,3,4 |
| --------------- | ---------------- | ----------------- |
Таблица: утилиты
| --------------- | ---------------- |
| ID | Устройство |
| --------------- | ---------------- |
|1 |Динамики |
| --------------- | ---------------- |
|2 |ТВ |
| --------------- | ---------------- |
|3 |Smart TV |
| --------------- | ---------------- |
|4 | Веб-камера |
| --------------- | ---------------- |
Хочунапечатать что-то вроде этого:
Room1: Speakers, Smart TV, Web camera
Вот что у меня есть, confroomreport.php:
<?php
require_once("db.php");
$util = $conn->getDeviceList();
$arr = $conn->getConfRoomList();
?>
<table border='1'>
<tr>
<th>Room</th>
<th>Utilities</th>
</tr>
<?php for( $i=0; $i < count($arr); $i++) {
print_r ("<tr>
<td>".$arr[$i]['name']."</td>
<td>".$arr[$i]['utilities']."</td>
</tr>"); } ?>
</table>
и db.php
public function getDeviceList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, device from utilities order by device ASC");
$statement->bind_result($id, $device);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "device" => $device];
}
$statement->close();
return $arr;
}
public function getConfRoomList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, name, utilities from rooms order by name ASC");
$statement->bind_result($id, $name, $utilities);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "name" => $name, "utilities" => $utilities];
}
$statement->close();
return $arr;
}
РЕДАКТИРОВАТЬ обновленный код на основе принятого решения:
Я добавил это в свой db.php:
public function joinDevRoom()
{
$arr = array();
$statement = $this->conn->prepare("SELECT r.name,GROUP_CONCAT(u.device) FROM room 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()) {
$arr[] = [ "id" => $id, "utilities" => $utilities];
}
$statement->close();
return $arr;
}
, и это мой обновленный confroomreport.php:
<?php
require_once("db.php");
$arr = $conn->getConfRoomList();
$join = $conn->joinDevRoom();
?>
<table border='1'>
<tr>
<th>Room</th>
<th>Utilities</th>
</tr>
<?php for( $i=0; $i < count($arr); $i++) {
print_r ("<tr>
<td>".$arr[$i]['name']."</td>"); }
for( $u=0; $u < count($join); $u++) {
print_r ("<td>".$join[$u]['utilities']."</td>
</tr>"); } ?>
</table>