phparraysmultidimensional-arraysumgrouping

Group rows of a 2d array by an identifying column and sum another column within each group


I want to merge rows with the same id into a single row and sum the pageview values.

[
    ['id' => 17088, 'PageView' => 5575],
    ['id' => 17088, 'PageView' => 4338],
    ['id' => 1121, 'PageView' => 3922],
    ['id' => 11397, 'PageView' => 2625],
    ['id' => 9638, 'PageView' => 2541],
    ['id' => 11397, 'PageView' => 2377],
    ['id' => 1121, 'PageView' => 10],
]

Desired result:

[
    ['id' => 17088, 'PageView' => 9913],
    ['id' => 1121, 'PageView' => 3932],
    ['id' => 11397, 'PageView' => 5002],
    ['id' => 9638, 'PageView' => 2541],
]

Solution

  • It's very simple :

    $grouped = [];
    
    foreach ($array as $row)
      $grouped[$row['id']] = ($grouped[$row['id']] ?? 0) + $row['PageView'];
    
    print_r($grouped);