在数组中对值进行分组

时间:2014-09-29 03:23:59

标签: php multidimensional-array unique-values

我已经做了大量的互联网搜索以找到我的问题的解决方案,但没有任何方法适用于我的具体案例。

我有一个小时和活跃用户数组如下:

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

我正在尝试对所有值进行分组,其中[时间]相同并获得该时间内的用户平均值。因此,在此示例中,07:00的用户为2,33,并舍入为2.

我试图尽可能清楚,并希望,这有点意义......

2 个答案:

答案 0 :(得分:2)

创建一个新数组,其中键是时间,值是该时间的用户值数组。然后通过将值的总和除以元素的数量,将值转换为平均值。

$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);

答案 1 :(得分:0)

好吧,由于你的数据结构如何,你将不得不两次通过。首先,您需要以可变的方式格式化数据。完成后,您可以继续计算平均值。

给出一些数据:

$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],
];

重新格式化以使其可用:

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

然后计算平均值:

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);