Question: Simple code like this:

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

```

output:

[![enter image description here](https://i.stack.imgur.com/1n1ec.png)](https://i.stack.imgur.com/1n1ec.png)

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 :)

Answer: 
I used [Collection](https://laravel.com/docs/8.x/collections#introduction) and end up with the correct results. This could be achieve in a number of ways:

**APPROACH 1:**

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

```

**APPROACH 2:**

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

```

**APPROACH 3:**

```php
$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);

```
You could use a single foreach and pre-set and array with the months 1-12 as the key and 0 for the value using [array\_fill\_keys](https://www.php.net/manual/en/function.array-fill-keys.php).

In the foreach you can get the first key and value using [key](https://www.php.net/manual/en/function.key.php) and [reset](https://www.php.net/manual/en/function.reset.php).

```
$array = [
    [11 => 771725],
    [11 => 847226],
    [10 => 410035],
    [11 => 455387],
];

$result = array_fill_keys(range(1,12), 0);
foreach ($array as $a) {
    $result[key($a)] += reset($a);
}

print_r($result);

```

Output

```
Array
(
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
    [10] => 410035
    [11] => 2074338
    [12] => 0
)

```

[Php demo](https://3v4l.org/Tf1QZ)