phparraysmultidimensional-arrayarray-columnarray-sum

How to Sum Columns of a Multi-Dimensional Array?


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?


Solution

  • 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;
    }