0

I want to sum the value of one key (qty) if has the same ID of n numbers of arrays inside an array, in this example I have only 2 arrays but I could have 1000

           $a = array(
            array(
                "id"=>1, 
                "qty"=>2
            ), 
            array(
                "id"=>1, 
                "qty"=>4
            )
            ...n arrays
            );
            

I want the result like this...

            $b = array(
            array(
                "id"=>1, 
                "qty"=>6
            ));

I want a function to pass variable $a with n numbers of arrays and returned $b. Thank you

Gustavo Morillo
  • 385
  • 3
  • 7
  • 2
    Does this answer your question? [How to sum all column values in multi-dimensional array?](https://stackoverflow.com/questions/1496682/how-to-sum-all-column-values-in-multi-dimensional-array) – Tom Nov 27 '20 at 11:54

1 Answers1

0

resolved

    $result = array();
    foreach($array as $k => $v) {
        $id = $v['id'];
        $result[$id][] = $v['quantity'];
    }

$new = array();
foreach($result as $key => $value) {
    $new[] = array('id' => $key, 'quanity' => array_sum($value));
}
echo '<pre>';
print_r($new);
?>
Gustavo Morillo
  • 385
  • 3
  • 7