user13957687
user13957687

Reputation:

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]
]

Upvotes: 2

Views: 74

Answers (2)

Michael Mano
Michael Mano

Reputation: 3440

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
  ]
]

Upvotes: 0

gguney
gguney

Reputation: 2643

You can loop over your array and set it to the another array like this:

$array = [
    ['id' => 1, 'value' => 2],
    ['id' => 1, 'value' => 3],
    ['id' => 2, 'value' => 5],
];

$temp = [];

foreach($array as $element){
    if(!isset($temp[$element['id']])){
        $temp[$element['id']] = [];
    }
    
    $temp[$element['id']][] = $element['value'];
}


var_dump($temp);

Upvotes: 0

Related Questions