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

在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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化