1

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!

5
  • Nope, that's the most efficient method I can think of too. Since you're matching them against nested arrays. Commented Sep 22, 2012 at 0:28
  • 1
    Check this one out: stackoverflow.com/questions/1496682/… Commented Sep 22, 2012 at 0:30
  • @kech You posted the same comment 3 times. Commented Sep 22, 2012 at 0:36
  • 1
    The only thing I can think of is make sure $asked exists in the array before looping through it. Commented Sep 22, 2012 at 0:39
  • @Barmar Sorry about that, I'm working my phone and I submit the comment too many times. Commented Sep 22, 2012 at 0:42

3 Answers 3

2

Using array_reduce:

$key = 3;

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

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

    return $memo;

});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
 $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;
    } 
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.