Reputation: 1727
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
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
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