У меня есть 5-уровневый вложенный массив, и я хочу сортировать его по-своему.Custom Array Sorting in PHP
После некоторой сортировки структуры является:
[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
)
)
Результат я хочу, чтобы сгруппировать массив по стране и это нравится:
[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
)
Это мой код до сих пор:
<?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; ?>
Но оно отображает только последнее значение для каждой страны
UPDATE + ОТВЕТ:
Это обновленный код, который делает именно то, что я хотел сделать.
$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; ?>
[Проверка аналогичной связи выпуск] (http://stackoverflow.com/q/25301224/2679536) –
это не сортировка. Это своего рода реорганизация/перегруппировка массивов. –