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;
}
Domanda
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?
Soluzione
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;
}
Altri suggerimenti
$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
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);
"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]