Как вычислить среднее значений одинаковых ключей в массиве php

Виктор

Есть массив

Array
(
    [0] => Array
        (
            [name] => rate-1-1
            [value] => 2
        )

    [1] => Array
        (
            [name] => rate-1-2
            [value] => 2
        )

    [2] => Array
        (
            [name] => rate-1-3
            [value] => 4
        )

    [3] => Array
        (
            [name] => rate-2-2
            [value] => 4
        )

    [4] => Array
        (
            [name] => rate-2-5
            [value] => 3
        )

    [5] => Array
        (
            [name] => rate-3-1
            [value] => 3
        )

    [6] => Array
        (
            [name] => rate-1-1
            [value] => 1
        )

    [7] => Array
        (
            [name] => rate-1-2
            [value] => 2
        )

    [8] => Array
        (
            [name] => rate-1-3
            [value] => 4
        )

    [9] => Array
        (
            [name] => rate-2-1
            [value] => 3
        )

    [10] => Array
        (
            [name] => rate-2-2
            [value] => 3
        )

    [11] => Array
        (
            [name] => rate-2-3
            [value] => 3
        )

    [12] => Array
        (
            [name] => rate-3-2
            [value] => 3
        )

)

Как вычислить среднее арифметическое значений "value" одинаковых ключей "name" в массивах php? Таких масссивов в массиве 100000

1 ответ

Виктор

$input = [исходный массив];
$out = [];

foreach($input as $e){
    if(!isset($out[$e['name']])) $out[$e['name']] = [];
    $out[$e['name']][] = $e['value'];
}

foreach($out as $key => $e){
    echo "$key = ".(array_sum($e)/count($e));
}

PS Ну и если Visman прав на счет SQL-запроса, то так

SELECT name, AVG(value) AS average FROM table GROUP BY name

licensed under cc by-sa 3.0 with attribution.