我正在处理一个统计信息仪表板,我想在其中显示一些按日历周排序的统计信息。
我正在使用以下格式在多维数组中获取数据:
Array
(
[success] => 1
[stats] => Array
(
[0] => Array
(
[year] => 2018
[week] => 14
[sum] => 18
[country] => at
)
[1] => Array
(
[year] => 2018
[week] => 14
[sum] => 907
[country] => de
)
[2] => Array
(
[year] => 2018
[week] => 15
[sum] => 2
[country] =>
)
[3] => Array
(
[year] => 2018
[week] => 15
[sum] => 65
[country] => at
)
[4] => Array
(
[year] => 2018
[week] => 15
[sum] => 237
[country] => de
)
)
)
我的问题是,不仅要按日历周分组,还要按国家/地区分组。我要获取的是一个数组,该数组按日历周分组。 sum
应该是同一周的每个sum
值的总和。
我需要的数组应如下所示:
Array
(
[success] => 1
[stats] => Array
(
[0] => Array
(
[year] => 2018
[week] => 14
[sum] => 925
)
[1] => Array
(
[year] => 2018
[week] => 15
[sum] => 304
)
)
)
country
不再需要,每个日历周应只有1个条目。
答案 0 :(得分:1)
类似的事情应该可以解决问题
$newArray = [];
foreach ($firstArray['stats'] as $entry) {
if (isset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])])) {
$newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['sum'] += $entry['sum'];
} else {
$newArray[sprintf('%d-%d', $entry['year'], $entry['week'])] = $entry;
}
}
编辑
$newArray = [];
foreach ($stats['stats'] as $entry) {
if (isset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])])) {
$newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['sum'] +=
$entry['sum'];
} else {
$newArray[sprintf('%d-%d', $entry['year'], $entry['week'])] = $entry;
}
unset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['country']);
}
$stats['stats'] = array_values($newArray);
@Rok D.谢谢您……我可以改编您的例子以完全满足我的需求。