How can PHP be used to aggregate and summarize data from arrays with multiple entries for the same key?

When dealing with arrays containing multiple entries for the same key, we can use PHP to aggregate and summarize the data by iterating through the array and updating the values for each key. One common approach is to use a loop to iterate through the array, checking if a key already exists in a new result array. If the key exists, we can aggregate the values accordingly. If the key does not exist, we can simply add it to the result array with its corresponding value.

// Sample array with multiple entries for the same key
$data = [
    ['key' => 'A', 'value' => 10],
    ['key' => 'B', 'value' => 20],
    ['key' => 'A', 'value' => 15],
    ['key' => 'C', 'value' => 30],
    ['key' => 'B', 'value' => 25]
];

// Initialize an empty result array
$result = [];

// Iterate through the data array and aggregate values for each key
foreach ($data as $item) {
    $key = $item['key'];
    $value = $item['value'];
    
    if (isset($result[$key])) {
        $result[$key] += $value;
    } else {
        $result[$key] = $value;
    }
}

// Output the aggregated data
print_r($result);