-2

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...

Gokigooooks
  • 794
  • 10
  • 20
  • 1
    Seems pretty straight-forward to me. What have you tried? – Mark Miller Sep 29 '14 at 03:27
  • I have tried with array_unique(), with serializing and unserializing, and many other things, but every time I got same array back. Maybe it would be easier, if i would do that at the same time as formatting times (from 8:13 to 8:00 etc.)? – powerthepower Sep 29 '14 at 03:32

2 Answers2

2

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);
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
  • You are my savior! I don't know what was wrong with me to not come with this idea. Probably I must have just overthinking :) – powerthepower Sep 29 '14 at 03:47
0

Well, because of how your data is structured you will have to do it in two passes. First you need to format the data in such a way that it becomes usable. Once that is done you can go ahead and calculate the averages.

Given some data:

$data = [
    ['time' => '05:00', 'users' => 0],
    ['time' => '06:00', 'users' => 0],
    ['time' => '07:00', 'users' => 1],
    ['time' => '07:00', 'users' => 3],
    ['time' => '07:00', 'users' => 3],
    ['time' => '08:00', 'users' => 0],
];

Reformat it so it becomes usable:

$coll = [];
foreach ($data as $item) {
    $time = $item['time'];
    if ( ! isset($coll[$time])) {
        $coll[$time] = [];
    }
    $coll[$time][] = $item['users'];
}

Then calculate the averages:

echo '<pre>';
foreach ($coll as $time => $entries) {
    $sum = array_sum($entries);
    $avg = round($sum / count($entries));
    echo "{$time} had an average of {$avg} users\n";
}
var_dump($coll);
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52