Search code examples
phparraysloopssumarray-column

Get the array sum of each column of each subarray


This is my array:

$array = [
    'HRI' => [
        [14157.72, 39140.94, 36383.66, 38508, 8424],
        [14157.72, 39140.94, 36383.66, 38508, 8424],
        [14157.72, 39140.94, 36383.66, 38508, 8424],
        [14157.72, 39140.94, 36383.66, 38508, 8424],
    ],
    'RHA' => [111562.5, 37880, 11364, 23719.5,  26705],
    'PBA' => [58816.26],
    'MPU' => [432]
];

I want to go through each subarray and get the sum for each column.

E.g.

For the sub array with the key HRI:

[HRI] => 
    Array (
        [0] => Array ( [0] => 14157.72 [1] => 10157.72 )
        [1] => Array ( [0] => 39140.94 [1] => 39140.94 )
        [2] => Array ( [0] => 36383.66 [1] => 36383.66 )
        [3] => Array ( [0] => 38508.00 [1] => 38508.00 )
        [4] => Array ( [0] => 8424.00 [1] => 8424.00 )
    )

expected output:

column 0:
  14157.72 + 39140.94 + 36383.66 + 38508.00 + 8424.00 = ?

column 1:
  10157.72 + 39140.94 + 36383.66 + 38508.00 + 8424.00 = ?

Solution

  • This should work for you:

    Just loop through the array and get the sum of each sub array with array_sum()

    foreach($arr as $k => $v)
        echo $k . " = " . array_sum($v) . "<br>";
    

    example input/output:

    $arr = [
            [1,2,3],
            [4,5,6],
            [7,8,9],
        ];
    

    output:

    0 = 6
    1 = 15
    2 = 24
    

    EDIT:

    Since you updated your array structure, just use this:

    foreach($arr as $k => $v)
        echo $k . " = " . array_sum(array_map("array_sum", $v)) . "<br>";
    

    EDIT 2:

    If you want the sum of each array of the sub arrays the you have to use two foreach loops like this:

    foreach($arr as $k1 => $innerArray) {
        foreach($innerArray as $k2 => $v)
            echo "$k1-$k2 = " . array_sum($v) . "<br>";
        echo "<br><br>";
    }
    

    EDIT 3:

    I think I finally see what you want: You just want to go through each sub arrays and get the sum of each column of the sub array:

    foreach($arr as $k1 => $innerArray) {
        foreach($innerArray[0] as $k2 => $v)
            echo "$k1-$k2 = " . array_sum(array_column($innerArray, $k2)) . "<br>";
        echo "<br><br>";
    }