在SQL请求之后,我有一个这样的表(方式更大,但这是一个例子):
host__id | Host | service__id | service_name
================================================
001 | Host 1 | 100 | Service 1
001 | Host 1 | 101 | Service 2
002 | Host 2 | 102 | Service 3
002 | Host 2 | 103 | Service 4
002 | Host 2 | 104 | Service 5
我想向每位主持人展示他的服务。 例如:Host1:Service1,Service2;主机2:服务3,服务4,服务5
我无法让它工作,因为同一主机会显示多次,我不想这样。
此外,表格一直在变化。这意味着我不知道将显示多少主机/服务。
我有什么想法可以做到这一点?谢谢!
编辑:这是我从该表中获取记录的SQL请求:
$displayhost = "SELECT T1.display_name as host_name,T1.host_object_id, T2.display_name as service_name,T2.service_object_id
FROM
nagios_hosts T1
INNER JOIN nagios_services T2
ON T1.host_object_id = T2.host_object_id
WHERE T2.service_object_id IN (".$ids.") ";
$selecthost = $db->prepare($displayhost);
$selecthost->execute([$ids]);
$hostdisplay = $selecthost->fetchall();
foreach ($hostdisplay as $display){
//the code I struggle with
}
答案 0 :(得分:0)
@xarj:您需要修改您的查询,除非这不会完美地运作。只需为您的主机名添加order by子句,即host 1,host 2。
我希望这会有所帮助:
$str = "";
foreach ($hostdisplay as $key => $display) {
$str .= $display["service_name"];
if ($key < count($hostdisplay) - 1 && $display["host_name"] == $hostdisplay[$key + 1]["host_name"]) {
$str .= ",";
} else {
echo $hostdisplay[$key]["host_name"] . ":" . $str;
echo "<br>";
$str = "";
}
}