0

I have an array with the following format

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 2000
            [4] => 2000
            [5] => 4000
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )

    [1] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 500
            [3] => 500
            [4] => 500
            [5] => 800
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )
 [2] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 500
            [3] => 500
            [4] => 500
            [5] => 800
            [6] => 5400
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
        )

)

i have tried using for and while loops but not getting the desired output I want the sum in the below format.

var a1=array[0][0]+array[1][0]+array[2][0];
var a2 = array[0][1]+array[1][1]+array[2][1];

etc

Thank You

iainn
  • 16,826
  • 9
  • 33
  • 40
prajakta
  • 21
  • 1
  • 8

3 Answers3

0

like you want to sum index number 3

$items = array(
 array(1 => 1, 2 => 'White Shirt', 3 => 2),
 array(1 => 2, 2 => 'Blue Shirt', 3 => 3)
);
echo "<pre>";
print_r($items);

echo array_sum(array_column($items, 3));

output is 5 of 3rd index

0

Short solution with call_user_function_array, array_map and array_sum functions:

$arr = [    // shortened version
    [0, 500, 500, 800],
    [0, 500, 800, 2000],
    [0, 500, 500, 5400],
];

$result = array_map(function($a){
    return array_sum($a);
}, call_user_func_array('array_map', array_merge([null], $arr)));

print_r($result);

The output:

Array
(
    [0] => 0
    [1] => 1500
    [2] => 1800
    [3] => 8200
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Here's a solution harnessing array_sum() and array_column(). It assumes each sub-array has the same number of values.

$arr = [ //<-- test data
    [4,1,6,8,3],
    [11,59,4,0,3],
    [2,4,8,8,131]
];

//for each 'column', sum the total across all sub-arrays
for($s=0; $s<count($arr[0]); $s++)
    ${'sum_'.$s} = array_sum(array_column($arr, $s));

echo $sum_4; //e.g. 137
Mitya
  • 33,629
  • 9
  • 60
  • 107