Skip to content
Advertisement

How to sum values from associative array if there is the same key in php laravel

Simple code like this:

        $array = [
            [11 => 771725],
            [11 => 847226],
            [10 => 410035],
            [11 => 455387],
        ];
        dd($array);

output:

enter image description here

The result in OCTOBER (10) there is 1 price:

["410035"]

while in NOVEMBER (11) there are 3 prices:

["771725", "847226", "455387"]

and at DECEMBER (12) is none

I need logic to calculate all prices in months 10, 11, and 12. The expected output is

[
    10 => "2074338",
    11 => "410035",
    12 => "0"
]

Thanks 🙂

Advertisement

Answer

I used Collection and end up with the correct results. This could be achieve in a number of ways:

APPROACH 1:

collect($array)
    ->groupBy(function ($item) {
        return collect($item)->keys()->first();
    })
    ->map(function ($items) {
        return collect($items)->flatten()->sum();
    });

APPROACH 2:

collect($array)
    ->groupBy(function ($item) {
        return array_key_first($item);
    })
    ->map(function ($items) {
      return collect($items)->flatten()->sum();
    });

APPROACH 3:

$default = [
    1 => 0, 
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0,
    6 => 0,
    7 => 0,
    8 => 0,
    9 => 0,
    10 => 0,
    11 => 0,
    12 => 0,
];

collect($array)
    ->reduce(function ($carry, $item) {
        $month = array_key_first($item);
  
        $carry[$month] += $item[$month];
  
        return $carry;
    }, $default);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement