-6

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.

Jearson
  • 411
  • 1
  • 7
  • 24

5 Answers5

2

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)));
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

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
Egretos
  • 1,155
  • 7
  • 23
0

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);
ilubis
  • 141
  • 1
  • 7
0

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)
}

https://3v4l.org/NbNVg

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

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,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136