0

Is there a way to create a group where a row match? Hard to explain but ill try.

If I have a database with these fields:

ID:  Name:      GROUP_ID:
1    Jacob      1
2    Jonathan   1
3    Jesper     2
4    Jeod       2
5    Jeod       3

and I have a function that retrieves all of this data using PDOStatement::fetchAll

$users = $page->retrieve_users();

and then I want each GROUP_ID to be in a grouped div.

Now this displays all the names

foreach($users as $user){

echo "<div>".$user["name"]."</div>";

}

How do I configure it so each user["name"] that has the same GROUP_ID is in a own div?

I know I have to create a new array for each different GROUP_ID but I dont even know how to do that since I want it to be flexible meaning if I add a new user with a unique GROUP_ID it will be sorted to its own.

Can anyone help me with this?

Thanks in advance!

2
  • Keep track of the current GROUP_ID and close / open your div when it changes. Assuming that the results are ordered by GROUP_ID... Commented Aug 29, 2014 at 14:29
  • Can you post the code for retrieve_users(); ? Commented Aug 29, 2014 at 14:29

3 Answers 3

2
  1. Categorize your users by group_id
  2. Loop over each group's users to display them

Example code

$groups = array();

foreach($users as $user){
  $group = $user["GROUP_ID"];
  if(!array_key_exists($group,$groups)){
    $groups[$group] = array();
  }
  $groups[$group][] = $user["name"];
}

foreach($groups as $group => $members){
  echo "This is group $group\n";
  foreach($members as $username){
    echo $username."\n"; 
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
$usersByGroup = array();
foreach($users as $user) {
    $usersByGroup[$user['group_id']][] = $user['user'];
}

This array looks like :

array(
    1 => array("Jacob", "Jonathan" ),
    2 => array("Jesper", "Jeod" ),
    3 => array("Jeod")
)

Comments

0
$user_name_array = array();
foreach ($users as $user) {
  $user_name_array[$user['GROUP_ID']][] = $user['Name'];
 }

foreach ($user_name_array as $group_id => $user_names) {
  foreach ($user_names as $user_name) {
    echo "<div>$user_name</div>\n";
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.