How can duplicate values be combined and summed in a multidimensional array in PHP?
When dealing with a multidimensional array in PHP that contains duplicate values, we can combine those duplicates and sum their values to simplify the data structure. To achieve this, we can loop through the array, track unique values in a separate array, and sum the values for duplicates as we encounter them.
<?php
// Sample multidimensional array with duplicate values
$data = [
['item' => 'apple', 'quantity' => 2],
['item' => 'banana', 'quantity' => 3],
['item' => 'apple', 'quantity' => 1],
['item' => 'banana', 'quantity' => 2]
];
// Combine and sum duplicate values
$combinedData = [];
foreach ($data as $item) {
$itemName = $item['item'];
$quantity = $item['quantity'];
if (array_key_exists($itemName, $combinedData)) {
$combinedData[$itemName] += $quantity;
} else {
$combinedData[$itemName] = $quantity;
}
}
// Output the combined and summed data
print_r($combinedData);
?>
Keywords
Related Questions
- What are best practices for structuring PHP code to improve database interactions and prevent errors like the one mentioned in the forum thread?
- What are the advantages and disadvantages of using checkboxes instead of buttons in PHP forms for specific actions?
- What are the best practices for handling errors in database connections in PHP?