1

I have array data like :

[
    'A1' => [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    'A2' => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    'A3' => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];

I want to add the column values and produce a flat array of sums.

I want answer like this:

[2, 1, 0, 0, 0, 0, 0, 0, 0, 0]

Are there any array functions in php to do this? Otherwise how can I do this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
jaya
  • 327
  • 3
  • 4
  • 16
  • [What have you tried?](http://www.whathaveyoutried.com/) – John Conde Nov 20 '12 at 13:48
  • There is no function in PHP that will do this automatically, but two loops should do it. Have a go yourself. – Maccath Nov 20 '12 at 13:52
  • Related: [Sum each column of a 2d array](https://stackoverflow.com/q/28128398/2943403) – mickmackusa Jan 03 '23 at 09:42
  • Also related: [Calculate totals for each column of a two dimensional array (matrix)](https://stackoverflow.com/q/18768541/2943403) and [Get sum of arrays inside array](https://stackoverflow.com/q/53150004/2943403) – mickmackusa Jan 05 '23 at 14:31

4 Answers4

2

There's always custom code:

function array_sum_rows($arr) {
    $out = array();
    foreach ($arr as $row) {
        foreach ($row as $i => $val) {
            $out[$i] = isset($out[$i]) ? $out[$i] + $val : $val;
        }
    }
    return $out;
}
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
  • thanks for your reply. i am getting undifined offset error at line $out[$i] = $out[$i] ? $out[$i] + $val : $val; – jaya Nov 20 '12 at 14:07
0
$multiArray = ... //your array
$sumArray = array();
$i = 1;

foreach ($multiArray as $key => $array) {
    $sumArray[$i] = array_sum($array);
    $i++;
}

This would work with your array. You will get an array

http://php.net/manual/en/function.array-sum.php

Martin
  • 1,488
  • 1
  • 13
  • 16
0

Unfortunately loses the actual index in the transpose:

function array_transpose($arr) {
    return call_user_func_array(
        'array_map',
        array_merge(
            array(NULL),
            $arr
        )
    );
}

$transposedArray = array_transpose($myData);
$result = array_map('array_sum', $transposedArray);
var_dump($result);

But the indexes can be restored by

$result = array_combine(array_keys(end($myData)), $result);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

"Transpose" the input array (rotate the data 90 degrees so that columns become rows), then feed the new "rows" to array_map() so that each has array_sum() called upon it.

Code: (Demo)

$array = [
    'A1' => [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    'A2' => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    'A3' => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];

var_export(array_map('array_sum', array_map(null, ...array_values($array))));

*Calling array_values() is necessary before the spread operator (...) until using a php version that doesn't choke on string keys.

Produces flat output array: [2, 1, 0, 0, 0, 0, 0, 0, 0, 0]

mickmackusa
  • 43,625
  • 12
  • 83
  • 136