Search code examples
phparraysgroupingsub-array

Group a 2d array by a column and create a subarray from another column per group


I got an array like this.

array:3 [▼
  0 => array:2 [▼
    "id" => "1039"
    "total" => 2.3
  ]
  1 => array:2 [▼
    "id" => "1039"
    "total" => -3.0
  ]
  2 => array:2 [▼
    "id" => "10007"
    "total" => 15.5
  ]
]

I need "total" for same "id" in the same array. e.g For "id" = 1039 array should be

[2.3, -3.0]

For "id" = 10007 array should be

[15.5]

My desired array is

[
  [2.3, -3.0],
  [15.5]
]

Solution

  • You really want them keyed by the arrays ID.

    $arr = [ ["id" => "1039", "total" => 2.3],["id" => "1039","total" => -3.0],["id" => "10007","total" => 15.5]];
    
    $total = [];
    foreach($arr as $item) {
        $total[$item['id']][] = $item['total'];
    }
    

    That will return

    array:2 [
      1039 => array:2 [
        0 => 2.3
        1 => -3.0
      ]
      10007 => array:1 [
        0 => 15.5
      ]
    ]