简体   繁体   中英

Sum of multidimensional associative array PHP

Array 
( 
    [Sum_1] => Array 
                ( 
                    [0] => Array 
                        ( 
                            [e] => 1000001 
                            [u] => Test1 
                            [a] => 775.00 
                        ) 
                    [1] => Array 
                        ( 
                            [e] => 26 
                            [u] => Test2 
                            [a] => 555.00 
                        ) 
                ) 
    [Sum_2] => Array 
                ( 
                    [0] => Array 
                        ( 
                            [e] => 1000001 
                            [u] => Test1 
                            [a] => 110.00 
                        ) 
                ) 
    [Sum_3] => Array 
                ( 
                    [0] => Array 
                        ( 
                            [e] => 1000001 
                            [u] => Test1 
                            [a] => 444.00 
                        ) 
                ) 
)  

I want to convert above array to something like below. Do I need to use a foreach or can array_sum do this?

Array 
    ( 
        [Sum_1] => 1330.00
        [Sum_2] => 110.00
        [Sum_3] => 444.00
     )  

(I want to get the sum of element [a] of each section named Sum_1, Sum_2, Sum_3) Thanks for your help!

You could do like this:

$ret = array_map(function($val) {
  return array_sum(array_map(function($val) {
     return $val['a'];
  }, $val));
}, $array);

Prior to php 5.4:

function a_getter($val) {
    return $val['a'];
}
$ret = array_map(function($val) {
    return array_sum(array_map('a_getter', $val));
}, $array);

using foreach loop you can try this

$sums=array();
    foreach($ArrayOfSums as $Offset=>$ArrayOfResults){
        foreach($ArrayOfResults as $ResultOffset=>$Result){
            $sums[$Offset]+=$Result["a"];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM