0

I have two arrays with this structure

array1 = Array(0=>Array(4, 7, 0, 11), 1=> Array(5,7,6,18));
array2 = Array(0=>Array(5,1,7,13), 1=>Array(9,1,6,16));

I tried to calculate sum of this array by element like this => 4 + 5 = 9;

Array(0=>Array(9,8,7,24), 1=>Array(14, 8, 12, 34)); 
5
  • array_sum() and array_column() might help Commented May 11, 2014 at 18:26
  • Can you add exactly the input you have and the output you'd want? as @JakeGould said this is a bit confusing Commented May 11, 2014 at 18:27
  • So which values in which of the two arrays do you want summing? If you can't explain the problem clearly, it's not easy for us to provide a solution Commented May 11, 2014 at 18:28
  • I want to calculate sum per column, in the exempla above from array 1 extract element from first sub array, 4 and the same with array2, 5 and save into array Commented May 11, 2014 at 18:30
  • Eg: $array1 = Array(0 => Array(1,3), 1=>Array(5,7)); $array2 = Array(0 => Array(2,4), 1=>Array(10,2)); I want to calculate sum between this two array and the result might be $result = array(0=>Array(3, 7), 1=>Array(15,9)) Commented May 11, 2014 at 18:31

1 Answer 1

1

Just try with:

$array1 = [[4, 7, 0, 11], [5, 7, 6, 18]];
$array2 = [[5, 1, 7, 13], [9, 1, 6, 16]];

$output = array_map(function($a, $b){
    return array_map(function() {
        return array_sum(func_get_args());
    }, $a, $b);
}, $array1, $array2);

var_dump($output);

Output:

array (size=2)
  0 => 
    array (size=4)
      0 => int 9
      1 => int 8
      2 => int 7
      3 => int 24
  1 => 
    array (size=4)
      0 => int 14
      1 => int 8
      2 => int 12
      3 => int 34
Sign up to request clarification or add additional context in comments.

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.