PHP循环遍历一系列结果,只想回显某些项目一次

时间:2015-01-19 04:05:08

标签: php codeigniter foreach

我循环遍历一系列结果,但结果中的行有重复的名称。有没有办法只回显一次这个名字。解决方案可能是微不足道的,但目前我很难过。

以下是代码:

$service_query = $this->db->query('SELECT service_id, server_id, port, comment FROM services');

    foreach ($service_query->result() as $service)
    {
        $server_query = $this->db->query('SELECT server_id, name, host FROM servers WHERE server_id =' . $service->server_id);

        foreach ($server_query->result() as $server)
        {
            echo $server->name;
            echo $service->comment;
            echo $server->host;
            echo $service->port;
            echo '<br>';

        }
    }

结果如下:

Mail Server   IMAP (Secure)    XXX.XXX.XXX.XXX:993
Mail Server   POP3 (Secure)    XXX.XXX.XXX.XXX:995
Mail Server   POP3             XXX.XXX.XXX.XXX:110
Mail Server   IMAP             XXX.XXX.XXX.XXX:143
Web Server    Apache           XXX.XXX.XXX.XXX:80

仅供参考我在这个项目中使用codeigniter框架。

4 个答案:

答案 0 :(得分:0)

试试这个:

$query = $this->db->query('SELECT name, service_id, server_id, host, port, comment 
                              FROM services 
                              LEFT JOIN servers USING (server_id) 
                           ORDER BY servers.name');

$server_name = '';

foreach ($query->result() as $server)
{
    if($server_name != $server->name) {
        echo $server->name;
        $server_name = $server->name;
    } 
    else { echo '-/-/-' };

    echo $server->comment;
    echo $server->host;
    echo $server->port;
    echo '<br>';

}

答案 1 :(得分:0)

我通过在$ service之前查询$ server的数据库并在前面的循环中回显$ server-&gt; name来解决这个问题。这是我的解决方案。感谢大家的快速解答。

$server_query = $this->db->query('SELECT server_id, name, host FROM servers');

    foreach ($server_query->result() as $server)
    {
        echo $server->name;

        $service_query = $this->db->query('SELECT service_id, server_id, port, comment FROM services  WHERE server_id =' . $server->server_id);

        foreach ($service_query->result() as $service)
        {
            echo $service->comment;
            echo $server->host;
            echo $service->port;
            echo '<br>';

        }
    }

答案 2 :(得分:-1)

你的意思是&#34;邮件服务器&#34;数据是重复的?如果是这样,请考虑在查询中使用MySQL DISTINCT删除重复内容,请参阅示例here

答案 3 :(得分:-1)

因为我明白你需要什么。就像

它的SQL语法

改变它

'SELECT server_id, name, host FROM servers WHERE server_id =' . $service->server_id .' GROUP BY name'