I have an array with the following structure.
Is there a function which can combine elements together, summing the totals?
Thanks for any pointers on how to achieve this. I've included a section of the array here, and then lower down the hopeful result.
I can achieve this via creating a second array as I reinterate over a php mysql query, but this doesn't feel like a very efficient way of doing things.
Array
(
[1] => Array
(
[Y01MA] => Array
(
[O] => Array
(
[F] => Array
(
[1] => 4
[2] => 6
[3] => 1
)
[M] => Array
(
[1] => 5
[2] => 5
)
)
[P] => Array
(
[F] => Array
(
[2] => 4
[3] => 6
[4] => 1
)
[M] => Array
(
[1] => 1
[2] => 4
[3] => 5
)
)
)
[Y01MB] => Array
(
[O] => Array
(
[F] => Array
(
[1] => 7
[2] => 2
)
[M] => Array
(
[1] => 11
[2] => 1
[3] => 1
)
)
[P] => Array
(
[F] => Array
(
[2] => 3
[3] => 6
)
[M] => Array
(
[2] => 3
[3] => 9
[4] => 1
)
)
)
)
Ideally what I would then end up with is something like this
Array ( [1] => Array ( [O] => Array ( [F] => Array ( [1] => 18 [2] => 2 [3] => 0 [4] => 0 )
[M] => Array
(
[1] => 23
[2] => 0
[3] => 0
[4] => 0
)
)
[P] => Array
(
[F] => Array
(
[1] => 1
[2] => 11
[3] => 7
[4] => 1
)
[M] => Array
(
[1] => 4
[2] => 11
[3] => 8
[4] => 0
)
)
)
You need a recursive sum of array.
You can achieve this by a recursively reducing array using array_reduce
function.
function sumRecursive($carry, $item) {
if(is_array($item)){
return array_reduce($item, 'sumRecursive', $carry);
}
return $carry+$item ;
}
$sum = sumRecursive(0, $arr);
Here's example working code: https://3v4l.org/FuGtf
Other way would to be utilize RecursiveArrayIterator
and RecursiveIteratorIterator
to iterate over the first one. ;-)
$sum = array_sum(
iterator_to_array(
new RecursiveIteratorIterator(
new RecursiveArrayIterator($arr)
),
false
)
);
Working code: https://3v4l.org/gEB6q
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments