Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Saturnlai's avatar

Sum value by key in array

I have one array in bellow

[
  [
    "start" => "2022-01-01 14:45:00"
    "end" => "2022-01-01 15:00:00"
    "attendees" => 2
  ],
  [
    "start" => "2022-01-01 14:45:00"
    "end" => "2022-01-01 15:00:00"
    "attendees" => 2
  ],
  [
    "start" => "2022-01-01 15:00:00"
    "end" => "2022-01-01 15:15:00"
    "attendees" => 2
  ],
  [
    "start" => "2022-01-01 15:15:00"
    "end" => "2022-01-01 15:30:00"
    "attendees" => 2
  ],
  [
    "start" => "2022-01-01 15:30:00"
    "end" => "2022-01-01 15:45:00"
    "attendees" => 2
  ],
  [
    "start" => "2022-01-01 15:45:00"
    "end" => "2022-01-01 16:00:00"
    "attendees" => 2
  ],
]

How to sum attendees by start in this array to create a new array

[
        {
            "start": "2022-01-01 14:45:00",
            "end": "2022-01-01 15:00:00",
            "attendees": 4
        },
        {
            "start": "2022-01-01 15:00:00",
            "end": "2022-01-01 15:15:00",
            "attendees": 2
        },
        {
            "start": "2022-01-01 15:15:00",
            "end": "2022-01-01 15:30:00",
            "attendees": 2
        },
        {
            "start": "2022-01-01 15:30:00",
            "end": "2022-01-01 15:45:00",
            "attendees": 2
        },
        {
            "start": "2022-01-01 15:45:00",
            "end": "2022-01-01 16:00:00",
            "attendees": 2
        }
    ]
0 likes
2 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Here is my tinkering :)

$data = collect([
  [
    "start" => "2022-01-01 14:45:00",
    "end" => "2022-01-01 15:00:00",
    "attendees" => 2,
  ],
  [
    "start" => "2022-01-01 14:45:00",
    "end" => "2022-01-01 15:00:00",
    "attendees" => 2,
  ],
  [
    "start" => "2022-01-01 15:00:00",
    "end" => "2022-01-01 15:15:00",
    "attendees" => 2,
  ],
  [
    "start" => "2022-01-01 15:15:00",
    "end" => "2022-01-01 15:30:00",
    "attendees" => 2,
  ],
  [
    "start" => "2022-01-01 15:30:00",
    "end" => "2022-01-01 15:45:00",
    "attendees" => 2,
  ],
  [
    "start" => "2022-01-01 15:45:00",
    "end" => "2022-01-01 16:00:00",
    "attendees" => 2,
  ],
])->groupBy('start')->map(function($group) {
  return [
    'start' => $group[0]['start'],
    'end' => $group[0]['end'],
    'attendees' => $group->sum('attendees'),
  ];
})->values();
1 like

Please or to participate in this conversation.