I'm trying to insert high level product review data to SKU records but am stuck with trying to get the average value of duplicated keys.
Array
(
[0] => Array
(
[sku] => 70835
[rating] => 5
)
[1] => Array
(
[sku] => F6W/35
[rating] => 5
)
[2] => Array
(
[sku] => 36865
[rating] => 5
)
[3] => Array
(
[sku] => 36835
[rating] => 5
)
[4] => Array
(
[sku] => F30W/T8/830/POLYLUX
[rating] => 2
)
[5] => Array
(
[sku] => 70835
[rating] => 4
)
)
I would like to get the average rating for the duplicate skus so expected output would be:
Array
(
[0] => Array
(
[sku] => 70835
[rating] => 4.5
)
[1] => Array
(
[sku] => F6W/35
[rating] => 5
)
[2] => Array
(
[sku] => 36865
[rating] => 5
)
[3] => Array
(
[sku] => 36835
[rating] => 5
)
...
)
I have the below loop which is summing the duplicates but I'm struggling to get the average
foreach ($reviews as $val) {
if (!isset($result[$val['sku']]))
{
$result[$val['sku']] = $val;
}
else{
$result[$val['sku']]['rating'] += $val['rating'];
#This will sum the duplicated ratings but I need to divide the sum here by the number of times the 'sku' index was duplicated so in the example 9/2 = 4.5
}
}
thanks in advance!
What about adding a count field to your result array...