Sum Up Values of Objects with Same Keys
In certain programming scenarios, you may encounter situations where you need to combine the values of multiple objects that share a specific key. For instance, consider an array of objects representing products:
[ { 'name': 'Product 1', 'quantity': 5 }, { 'name': 'Product 1', 'quantity': 3 }, { 'name': 'Product 2', 'quantity': 10 }, { 'name': 'Product 3', 'quantity': 25 } ]
The task is to sum up the quantity values for products with the same name. This results in a new array where each product has its combined quantity:
[ { 'name': 'Product 1', 'quantity': 8 }, { 'name': 'Product 2', 'quantity': 10 }, { 'name': 'Product 3', 'quantity': 25 } ]
To achieve this, follow these steps:
By following these steps, you can effectively sum up the values of objects with the same keys, allowing you to perform mathematical operations on grouped data.
The above is the detailed content of How to Sum the Values of Objects with Identical Keys?. For more information, please follow other related articles on the PHP Chinese website!