Answer
Solution:
Assuming you have an array of arrays (it's not clear from your code that that is so) then you can usearray_column()
to step across the columns, andarray_sum()
andcount()
to calculate the averages.
<?php
$rate = [
["1.55","1","1","1"],
["2.55","2.55","2.55","2.55"],
["1","1","1","1"],
["1.2","1.21","1.2","1.2"]
];
$results =[];
// Count the columns in the first row
for ($i = 0; $i<sizeof ($rate[0]); $i++) {
// Extract each column in turn
$col = array_column($rate, $i);
// Calculate and store the averages
$results[]= array_sum($col)/count($col);
}
var_dump($results);
Output
array(4) {
[0]=>
float(1.575)
[1]=>
float(1.44)
[2]=>
float(1.4375)
[3]=>
float(1.4375)
}
Update:
Since the OP has now posted some real data, it needs a little preprocessing before this code will work. The original data is stored in a database as JSON strings, so these need to be extracted and decoded.array_map()
does this nicely.
// Array with new database data
$dbData = [
["rate"=>'["1.55","1","1","1"]'],
["rate"=>'["2.55","2.55","2.55","2.55"]'],
["rate"=>'["1","1","1","1"]'],
["rate"=>'["1.55","2.55","3.55","4.56"]']
];
// array_map calls json_decode() on the 'rate' element of each array element
Method 1:
$rate = array_map(function($a){
return json_decode($a['rate']);
},$dbData);
// code from here on as above.
Method 2:
foreach ($dbData as $key => $ev){
$rate_data[] = $ev['rate'];
}
$rate_array = implode(', ',$rate_data);
$json_rate = '[ '. $rate_array .' ]'; //Json string
//convert JSON string to array
$rate = json_decode($json_rate, TRUE);
See: https://3v4l.org/X7haS
Note: It's rarely a good idea to store data in a database as JSON strings. If you'd taken the trouble to separate out the values in the JSON strings and store them in separate columns all this malarkey could be avoided by asking the database to return the averages directly.