'Sum array values of a column within each column of an array with 3 levels
I'm trying to use array_sum()
on columns within columns of a multidimensional array.
For eg: I have an array that looks like this:
$array = [
[['value' => 1100], ['value' => 1000], ['value' => 3000]],
[['value' => 1200], ['value' => 2000], ['value' => 2000]],
[['value' => 1300], ['value' => 4000], ['value' => 1000]],
];
I tried with:
$arr = [];
foreach($array as $point){
$arr[] = array_sum(array_column($array, $point[0]['value']));
}
print_r($arr);
but I'm expecting this output:
[['value' => 3600], ['value' => 7000], ['value' => 6000]]
Or more simply: [3600, 7000, 6000]
Tested here: https://onecompiler.com/php/3y3mxqky9
Solution 1:[1]
You can sum your columns doing like this:
foreach($array as $key => $point){
$arr[] = array_sum(array_column( array_column($array,$key),'value'));
}
print_r($arr);
Solution 2:[2]
Since you wish to have the sum vertically and not horizontally, the array_column style you used won't work. You can simply achieve this with 2 nested loops like below:
<?php
$arr = [];
foreach($array as $point){
foreach($point as $k => $v){
$arr[$k] = ($arr[$k] ?? 0) + $v['value'];
}
}
print_r($arr);
Solution 3:[3]
Transpose your input array, then isolate and sum the value
column of data.
The variadic offering of $array
to array_map()
is the transposing part.
In other words, array_map(fn(...$col) => $col, ...$array)
converts rows of data into columns of data.
Code: (Demo)
var_export(
array_map(
fn(...$col) => array_sum(array_column($col, 'value')),
...$array
)
);
Output:
array (
0 => 3600,
1 => 7000,
2 => 6000,
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nicola Fiorello |
Solution 2 | nice_dev |
Solution 3 | mickmackusa |