phparraysmultidimensional-arraygroupingsub-array

Group 2d array data by the values in a column


I'm struggling with results from a database fetch.

Let's say I have some rows:

array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'), 
array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'), 
array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'), 
array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'), 
array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest') 

now what do I have to do to put these 5 rows into a grouped array?

example:

user = array(
   array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'), 
   array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'))
guest = array(
   array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'), 
   array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest')) 
admin = array(
   array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'))

Solution

  • // get query result
    $result = mysql_query(...);
    
    // prepare the target array
    // it will hold user groups having group name as key
    // eg. "user" => Array(), "guest" => Array()
    $users = Array();
    
    // whlile fetching rows from the result, add each row into $row["group"] key of target
    while($row = mysql_fetch_assoc($result))
       $users[$row["group"]][] = $row;
    
    // free the mysql result
    mysql_free_result($result);
    

    Update: There is no real need to define the keys in the target $user variable. to make code readable and manageable it is enough to comment on the general structure.