duanpie4763 2016-07-27 12:38
浏览 93
已采纳

在PHP foreach循环中对项目进行分组[关闭]

I want somehow to group items in foreach loop so i can display them effectively. For example if I have the following MySql table:

user_id username group_id
1       John     1
2       Mark     2
3       Steve    2

I want the users in the group_id 2 to be shown together in <div class="group2">Username 1: Mark, Username 2: Steve</div> and users in group_id 1 <div class="group1">Username John</div>

I hope you will understand the question.

  • 写回答

3条回答 默认 最新

  • dql7588 2016-07-27 12:45
    关注

    You can do this fairly easily by ordering your query by group_id and then keeping track of when it changes. Something like this:

    $query = "SELECT * FROM table ORDER BY group_id";
    $results = $mysqli->query($query);
    $lastGroup = 0;
    while ( $row = $results->fetch_assoc() )
    {
        if ( $row['group_id'] != $lastGroup )
        {
            // If there is already a div open we need to close it, so if 
            // last group > 0 then a div has been opened.
            echo ($lastGroup > 0 ? '</div>' : '') . '<div class="group' . $row['group_id'] . '">';
        }
        $lastGroup = $row['group_id'];
        echo $row['username'] . '<br>';
    }
    // close the last open div
    echo '</div>';
    

    Alternatively you can use the MySQL GROUP_CONCAT function to get back all the usernames in a group. Use this:

    $query = "SELECT group_id,
    GROUP_CONCAT(username) as users
    FROM table
    GROUP BY group_id";
    
    $results = $mysqli->query($query);
    while ( $row = $results->fetch_assoc() )
    {
        echo '<div class="group' . $row['group_id'] . '">' . $row['users'] . '</div>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟