<?php
$array = [
"Jan 2016" => 2,
"Feb 2016" => 4,
"Mar 2016" => 2,
"Apr 2016" => 0,
"Jan 2017" => 9,
"Feb 2017" => 2,
"Mar 2017" => 5,
"Jan 2018" => 4,
"Feb 2018" => 6
];
$totals = [];
foreach ($array as $date => $amount) {
$year = substr($date, -4);
$totals[$year] = ($totals[$year] ?? 0) + $amount;
}
var_export($totals);
- Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array (
2016 => 8,
2017 => 16,
2018 => 10,
)
preferences:
84.32 ms | 406 KiB | 5 Q