Search code examples
phpmultidimensional-arrayunique-values

Grouping values in array


I have done a lot of looking around the internet to find solution to my problem, but nothing has worked for my specific case.

I have an array of hours and active users as following:

Array ( 
    [0] => Array ( 
        [time] => 05:00 ,
        [users] => 0
        ),
    [1] => Array ( 
        [time] => 06:00,
        [users] => 0
        ),
    [2] => Array ( 
        [time] => 07:00,
        [users] => 1
        ),
    [3] => Array ( 
        [time] => 07:00,
        [users] => 3
        )
    [4] => Array ( 
        [time] => 07:00,
        [users] => 3
        ),
    [5]=> Array ( 
        [time] => 08:00,
        [users] => 0
        )
    ) 

I'm trying to group all the values, where [time] is same and get an average of users for that time. So in this example, users for 07:00 would be 2,33, and rounded to 2.

I tried to be clear as possible and am hoping, that this makes some sense...


Solution

  • Create a new array where the key is the time and the value is an array of user values for that time. Then convert the value into an average by dividing the sum of the value by its number of elements.

    $grouped_by_time = array();
    
    foreach($array as $element) {
        $grouped_by_time[$element['time']][] = $element['users'];
    }
    
    foreach($grouped_by_time as &$element) {
        $element = round(array_sum($element)/count($element));
    }
    
    print_r($grouped_by_time);