How to create array of groups and their users

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sarahaziz
    New Member
    • Oct 2008
    • 17

    How to create array of groups and their users

    Hello guys
    i want to create something like this image ,consider the fact that Group and users comes from 2 different tables but only one query.
    I want to add them into one array.
  • kovik
    Recognized Expert Top Contributor
    • Jun 2007
    • 1044

    #2
    So... what are you having difficulty with? Storing the users into an array, or displaying them into this format that you have given?

    Comment

    • sarahaziz
      New Member
      • Oct 2008
      • 17

      #3
      Since i get all data from only one query the group is repeated with each record i want to add it once in the array and then add users of this group after it in the array.
      How is that done?

      Comment

      • dlite922
        Recognized Expert Top Contributor
        • Dec 2007
        • 1586

        #4
        so if you have something like this:
        Code:
        John Doe    grpA 
        Jane Smith  grpB
        Helen Fake  grpA
        Tom Record  grpA
        Micky Mouse grpB
        Just use an associative array with the group being the key and each name list will be another array

        Code:
        $data = array(); 
        
        while($row = mysql_fetch_assoc($resource))
        {
           $group = $row['group_name']; 
           $name = $row['person_name'];
        
           $data[$group][] = $name; 
        
        }
        That should do it.

        Dan

        Comment

        • kovik
          Recognized Expert Top Contributor
          • Jun 2007
          • 1044

          #5
          That's quite graceful. I was going to suggest the direct echoing method when you order the items by group in the SQL and then output the group name whenever the group changes.

          Code:
          $result = mysql_query("select * from users order by group asc");
          $current_group = null;
          
          echo '<ul>';
          
          while ($data = mysql_fetch_object($result)) {
              if ($current_group != $data->group) {
                  $current_group = $data->group;
                  echo "<li><strong>{$data->group}</strong></li>";
              }
              
              echo "<li>{$data->user}</li>"
          }
          
          echo '</ul>';

          Comment

          Working...