确定数组列的平均值

时间:2013-12-20 10:04:57

标签: php arrays multidimensional-array

考虑下面的数组: -

Array
(
[0] => Array
    (
        [0] => 99895
        [1] => 35378
        [2] => 0.01

    )

[1] => Array
    (
        [0] => 99895
        [1] => 813
        [2] => -0.97

    )

[2] => Array
    (
        [0] => 99895
        [1] => 771
        [2] => 0.29

    )

[3] => Array
    (
        [0] => 442
        [1] => 833
        [2] => -1.06

    )

[4] => Array
    (
        [0] => 442
        [1] => 485
        [2] => -0.61

    )

[5] => Array
    (
        [0] => 442
        [1] => 367
        [2] => -0.14

    )

[6] => Array
    (
        [0] => 442
        [1] => 478
        [2] => 0.77

    )

[7] => Array
    (
        [0] => 442
        [1] => 947
        [2] => -0.07

    )

[8] => Array
    (
        [0] => 7977
        [1] => 987
        [2] => 0.76

    )

[9] => Array
    (
        [0] => 7977
        [1] => 819
        [2] => 0.37

    )

[10] => Array
    (
        [0] => 7977
        [1] => 819
        [2] => 0.36

    )

[11] => Array
    (
        [0] => 7977
        [1] => 653
        [2] => 1.16

    )

[12] => Array
    (
        [0] => 7977
        [1] => 1653
        [2] => 1.15
    )

)
从上面的数组

我将如何确定下面的数组?

array
(
    99895 => -0.223

    442 => -0.22

    7977 => 0.76
)

实际上我需要第1栏第3栏的平均值。

1 个答案:

答案 0 :(得分:2)

首先将所有第3列元素收集到一个键入第1列的数组中:

$arrays = array();
foreach ($input as $vals) {
    $key = $vals[0];
    $val = $vals[2];
    if (isset($arrays[$key])) {
        $arrays[$key][] = $val;
    } else {
        $arrays[$key] = array($val);
    }
}

现在浏览所有这些,计算平均值:

foreach ($arrays as &$array) {
    $array = array_sum($array)/count($array);
}