How can I add all the columnar values by associative key? Note that key sets are dynamic.
Input array:
Array
(
[0] => Array
(
[gozhi] => 2
[uzorong] => 1
[ngangla] => 4
[langthel] => 5
)
[1] => Array
(
[gozhi] => 5
[uzorong] => 0
[ngangla] => 3
[langthel] => 2
)
[2] => Array
(
[gozhi] => 3
[uzorong] => 0
[ngangla] => 1
[langthel] => 3
)
)
Desired result:
Array
(
[gozhi] => 10
[uzorong] => 1
[ngangla] => 8
[langthel] => 10
)
this works great on my laravel project
You can use
array_walk_recursive()
to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).Example with
array_walk_recursive()
for the general caseAlso, since PHP 5.5 you can use the
array_column()
function to achieve the result you want for the exact key,[gozhi]
, for example :Example with
array_column()
for the specified keyIf you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :
Example with
array_column()
in case all inner arrays have the same keysIf you want a general-case solution using
array_column()
then at first you may consider to get all unique keys , and then get the sum for each key :Example with
array_column()
for the general caseFor example, you can pluck all fields from a result like this below.
I am picking out the 'balance' from an array and save to a variable
then on the next line u can sum like this:
Hope it helps.
It can also be done using
array_walk
:Not so readable like previous solutions but it works :)
We need to check first if array key does exist.
CODE:
OUTPUT With Array Key Validation:
OUTPUT Without Array Key Validation:
This is a bad practice although it prints the output. Always check first if key does exist.
For those who landed here and are searching for a solution that merges N arrays AND also sums the values of identical keys found in the N arrays, I've written this function that works recursively as well. (See: https://gist.github.com/Nickology/f700e319cbafab5eaedc)
Example:
Will result in:
Here's the code: