Jenny
Jenny

Reputation: 1727

How to Sum the same element from different arrays in php?

I have arrays like this: array('id'=>value,'id'=>value)

$arrays=array(
    [0] => Array ( [3] => 1, [102] => -1, [15] => 1,)            
    [1] => Array ( [5] => 1, [80] => -1 )                 
    [2] => Array ( [99] => -1, [3] => -1,[5] => 1 ) 
)

I need to get the total result of a given key. In the above example, if ask for id of 3, the sum is 0, if ask for id of 5, the sum is 2. I can only think of something like this:

  foreach($arrays as $array){
    foreach( $array as $id=>$v){
     if( $id == $asked )
        $total = $total + $v;
    }
  }

Somehow I guess there has to be an efficient way to do the job. I would like to learn. Thanks!

Upvotes: 1

Views: 331

Answers (3)

Ouadie
Ouadie

Reputation: 13185

 $prec_array=end($arrays);
 foreach($arrays as $array){
    foreach($array as $id=>$v){
     if(array_key_exists($id, $prec_array) )
            $total[$id] += $v + $prec_array[$id] ;
    $prec_array = $array;
    } 
 }

Upvotes: 0

Mr. 14
Mr. 14

Reputation: 9528

foreach($arrays as $array) {
    $total += $array[$id];
}

Upvotes: 0

moonwave99
moonwave99

Reputation: 22817

Using array_reduce:

$key = 3;

$sum = array_reduce($arrays, function(&$memo, $item) use($key){

    array_key_exists($key, $item) && $memo += $item[$key];

    return $memo;

});

Upvotes: 2

Related Questions