I need to calculate the average value for each column of data in an array of associative arrays. The result should be a flat, associative array of averages.
Sample array:
$array = [
[
"a" => 0.333,
"b" => 0.730,
"c" => 0.393
],
[
"a" => 0.323,
"b" => 0.454,
"c" => 0.987
],
[
"a" => 0.753,
"b" => 0.983,
"c" => 0.123
]
];
I am looking for a simpler way of processing all the array elements and producing a single array which has a mean value (average) of all the corresponding values.
My current code works, but I'm hoping for a more elegant approach.
$a = []; // Store all a values
$b = []; // Store all b values
$c = []; // Store all c values
for ( $i = 0; $i < count( $array ); $i ++ ) {
// For each array, store each value in it's corresponsing array
// Using variable variables to make it easy
foreach ( $array[ $i ] AS $key => $val ) {
$k = $key;
$$k[] = $val;
};
}
// Create single array with average of all
$fa = array(
'a' => array_sum($a) / count($a),
'b' => array_sum($b) / count($b),
'c' => array_sum($c) / count($c)
);
The desired result:
[
'a' => 0.4696666666666667,
'b' => 0.7223333333333333,
'c' => 0.501,
]
Assuming each sub-array has the same keys:
foreach(array_keys($array[0]) as $key) {
$result[$key] = array_sum($tmp = array_column($array, $key))/count($tmp);
}