Barba Barba - 1 year ago 44
SQL Question

Grouping items in PHP foreach loop

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.

Answer Source

Create a 2D array:


Foreach results row $row:

$users[$row->group_id][$row->user_id] = $row->username;


foreach($users as $group_id -> $group_users) {
    echo '<div class="' . $group_id . '">';
    foreach($group_users as $user_id -> $username) {
        echo " Username: ";
        echo $user_id;
        echo " :";
        echo $username;
    echo "</div>";