I have a problem here and I hope it's interesting enough to get help from the SO community. I have declared an array in my PHP code that looks like this:
$array = array:4 [▼
0 => array:3 [▼
"a" => 0.333
"b" => 0.730
"c" => 0.393
]
1 => array:3 [▼
"a" => 0.323
"b" => 0.454
"c" => 0.987
]
2 => array:3 [▼
"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 i.e:
array (
a => average of a's
b => average of all b's
c => average of all c's
)
This is the code I wrote below (which works):
$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($ac/count($c)
);
I have a feeling this is not the most efficient way to achieve this given the numerous PHP functions out there dealing with arrays. I want to know if there is a simpler way of doing it and how. Thanks guys!