Group rows by column and sum another column within groups [duplicate]



PHP Snippet 1:

The reduced array but with the original indexes:
array (
  0 => 
  array (
    'tag_id' => '6291',
    'az' => 9,
  ),
  2 => 
  array (
    'tag_id' => '6311',
    'az' => 4,
  ),
  3 => 
  array (
    'tag_id' => '6427',
    'az' => 4,
  ),
)
The reduced array with new indexes:
array (
  0 => 
  array (
    'tag_id' => '6291',
    'az' => 9,
  ),
  1 => 
  array (
    'tag_id' => '6311',
    'az' => 4,
  ),
  2 => 
  array (
    'tag_id' => '6427',
    'az' => 4,
  ),
)

PHP Snippet 2:

$res = array_reduce(
    $array,
    function($ac, $el) {
        $ac[$el['tag_id']] += $el['az'];
        return $ac;
    },
    []
);

print_r($res);

PHP Snippet 3:

Warning: Undefined array key 6291

Warning: Undefined array key 6311

Warning: Undefined array key 6427
Array
(
    [6291] => 9
    [6311] => 4
    [6427] => 4
)

PHP Snippet 4:

$res = array_map(
    fn($k, $v) => ['tag_id' => $k, 'az' => $v],
    array_keys($res),
    $res
);

PHP Snippet 5:

$arr = array(
    array("tag_id" => "6291", "az" => "int(5)"),
    array("tag_id" => "6291", "az" => "int(4)"),
    array("tag_id" => "6311", "az" => "int(4)"),
);

$results = array_filter($arr, function ($item) {
    if ($item["tag_id"] == "6291") {
         return true;   
    }
    return false; 
});
              
foreach ($results as $result) {
    echo "tag_id = " . $result["tag_id"];    
    echo "az = " . $result["az"] . PHP_EOL;
}