I have a 5 level nested array and I want to sort it in a custom way.
After some sorting the structure is:
[shortcode1] => Array
(
[country1] => Array
(
[count] => 10
[revenue_value] => 11
)
)
[shortcode2] => Array
(
[country1] => Array
(
[count] => 24
[revenue_value] => 52
)
)
[shortcode3] => Array
(
[country2] => Array
(
[count] => 25
[revenue_value] => 52
)
)
The result I want is to group the array by country and have it like:
[country1] => Array
(
[count] => 34 // sum of all counts of country1
[revenue_value] => 63 // sum of all revenue_values of country1
)
[country2] => Array
(
[count] => 25 // sum of all counts of country2
[revenue_value] => 52 // sum of all revenue_values of country2
)
This is my code so far:
<?php foreach ($country_shortcode as $shortcode):
$count = 0;
$revenue = 0;
?>
<?php foreach ($shortcode as $country=>$value): ?>
<?php
$count += $value['count'];
$revenue += $value['revenue_value'];
$country_sum[$country] = array(
'count' => $count,
'revenue' => $revenue,
);
?>
<?php endforeach; ?>
<?php endforeach; ?>
But it only displays the last value per country
UPDATE + ANSWER:
This is the updated code that does exactly what I wanted to do.
$country_data;
<?php foreach ($country_shortcode as $shortcode):
$count = 0;
$revenue = 0;
?>
<?php foreach ($shortcode as $country=>$value): ?>
<?php
if (!isset($country_sum[$country])) $country_sum[$country] = array('count' => 0, 'revenue'=>0);
$country_sum[$country]['count'] += $value['count'];
$country_sum[$country]['revenue'] += $value['revenue_value'];
?>
<?php endforeach; ?>
<?php endforeach; ?>