'Get sum of arrays inside array
How do I get the sum of this arrays.
$arrays = [[0, 176000], [0,500], [0, 3960000]];
The output should be:
$arrays = [0, 4136500];
Any help will be much appreciated.
Solution 1:[1]
Using variadic arguments and null
callback for first array_map
:
$arrays = [[0, 176000], [0,500], [0, 3960000]];
print_r(array_map('array_sum', array_map(null, ...$arrays)));
Solution 2:[2]
In Larevel you can use collections. For example:
$a = collect([[0, 176000], [0,500], [0, 3960000]]);
$b = new Collection;
foreach ($a as $k => $e) {
$b->push ( $a->pluck($k)->sum() );
}
$c = $b->take(2); // Result is going to be here
Solution 3:[3]
this is using native way (but i think need to rework)
<?php
$arrays = [[0, 176000], [0,500], [0, 3960000]];
$new_arrays = [];
foreach ($arrays as $key => $val) {
$new_arrays[0] += $val[0];
$new_arrays[1] += $val[1];
}
print_r($new_arrays);
Solution 4:[4]
U_mulders answer works if there is no keys to to keep track of.
If you have an associative array then you need to loop the array and build add the values like:
$arrays = [[0,"A" => 176000], [0, "b" => 500], [0, 3960000, 200], [10, 500, 200]];
foreach($arrays as $sub){
foreach($sub as $key => $num){
if(!isset($new[$key])) $new[$key] =0;
$new[$key] += $num;
}
}
var_dump($new);
Output:
array(5) {
[0]=>
int(10)
["A"]=>
int(176000)
["b"]=>
int(500)
[1]=>
int(3960500)
[2]=>
int(400)
}
Solution 5:[5]
There is no need to call array_map()
more than once. Unpack the array using the spread operator (...
). This will deliver columns of data to the custom function's body. Return the sum of each column.
Code: (Demo)
$arrays = [[0, 176000], [0,500], [0, 3960000]];
var_export(
array_map(fn() => array_sum(func_get_args()), ...$arrays)
);
Or
var_export(
array_map(fn(...$col) => array_sum($col), ...$arrays)
);
Output (from either)
array (
0 => 0,
1 => 4136500,
)
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 | u_mulder |
Solution 2 | |
Solution 3 | ilubis |
Solution 4 | Andreas |
Solution 5 | mickmackusa |