Based on this link PHP sum array value based on textual duplicate in another array i have question if i change topic to PHP average array value based on textual duplicate in another array can anyone help? thanks in advanced
i need to average array value based on textual duplicate in another array from that link
Example
$dateclosed = array("28-09-2024", "30-09-2024", "30-09-2024", "30-09-2024", "16-09-2024");
$medpo = array(23.83, 17.27, 40.55, 34.11, 24.94);
So the result look like this
$dateclosed = array("28-09-2024", "30-09-2024", "16-09-2024");
$medpo = array(23.83, 30.64333333333333, 24.94);
from above
23.83 from 23.83/1
24.94 from 24.94/1
30.64333333333333 from (17.27+40.55+34.11)/3
From the linked example I tried this code:
$new_array_calc = array();
foreach($dateclosed as $key => $value) {
$new_array_calc[$value] = ($new_array_calc[$value] ?? 0) + $medpo[$key];
$new_array_calc[$value] = $new_array_calc[$value] / count($new_array_calc);
}
print_r($new_array_calc);
It shows:
Array ( [28-09-2024] => 23.83 [30-09-2024] => 29.35125 [16-09-2024] => 8.3133333333333 )
I don’t know how to find exactly count of each date such as 23.83(count one) 91.93(count three) 24.94(count one) and calculate in one line.
2
Answers
A simple way to do this is to apply the average calculation in a separate loop after you have populated the new array. That way, you’ve already got the final total value that you need to divide by. Doing it inside the
foreach($dateclosed...
loop can’t really work, because you don’t know if you’ve found the last entry for any given date yet, or not.The
array_count_values()
function will also help you here – it’s a quick way to tell you how many entries occur for each date in the original$dateClosed
array – which you need for the average calculation.Here’s a working example:
This outputs:
Live demo: https://3v4l.org/c0QJ5
To correctly calculate average values based on textual duplicates, you need to keep track of both sum and count of each date. Here’s another way, best for large data sets:
Result: