What are some common ways to group and total values in PHP arrays based on specific keys?
To group and total values in PHP arrays based on specific keys, you can use a combination of array functions like array_reduce, array_key_exists, and isset. First, iterate through the array and check if the key exists in a new result array. If it does, add the value to the existing total. If not, create a new key in the result array with the value.
$data = [
['key' => 'A', 'value' => 10],
['key' => 'B', 'value' => 20],
['key' => 'A', 'value' => 15],
['key' => 'C', 'value' => 5],
];
$result = array_reduce($data, function($carry, $item) {
if (array_key_exists($item['key'], $carry)) {
$carry[$item['key']] += $item['value'];
} else {
$carry[$item['key']] = $item['value'];
}
return $carry;
}, []);
print_r($result);
Related Questions
- Are there any recommended online books or tutorials for PHP 5 object-oriented programming?
- What is the recommended method to handle special characters, such as umlauts, in email subjects and senders when using PHP?
- What potential issues can arise when using regular expressions to filter specific patterns in PHP?