phparraysmultidimensional-arraygroupingresultset

Group query result set rows by month name


I really need some help to figure this one out.

I've got a number of arrays and i would like to merge some of them. It looks like as following.

while ($row = $db->fetch_array($result_set)) {
    $year           = $row['year(Tidspunkt)'];
    $month_num      = $row['month(Tidspunkt)'];
    $month      = $cal->name_of_month($row['month(Tidspunkt)']);
    $type           = $row['Klubtype'];
    $visits         = $row['count(Handling)'];
    $days_in_month = $cal->days_in_month($month_num,$year);
    $avg           = $visits / $days_in_month;
    $object_array[]= array('month' => $month , 'visits' => $visits, 'type' => $type, 'avg' => $avg);
}
return $month_array;

And the output looks like this

Array ( 
     [0] => Array ( [month] => Januar [visits] => 891 [type] => FK [avg] => 28.7419354839 ) 
     [1] => Array ( [month] => Januar [visits] => 23 [type] => UK [avg] => 0.741935483871 ) 
)

Now I would like to merge these two arrays based on the value of month. Imagine when I've got arrays for a whole year. Then it would be nice to have 12 arrays instead of 24.


Solution

  • I think this may be what you want...

    $newArray = array();
    
    foreach($array as $value) {
    
       $month = $value['month'];
       unset($value['month']);
       $newArray[$month][] = $value;
    }
    

    This will give you something like...

    Array ( 
         ['Januar'] => Array (
            [0] => Array( [visits] => 891 [type] => FK [avg] => 28.7419354839 ) 
            [1] => Array ( [visits] => 23 [type] => UK [avg] => 0.741935483871 ) 
    )