0

I have two arrays. They are always the same length. If the first array element value is the same then sum of the second array element value.

Example

$array1 = array(1,2,2,3);
$array2 = array(10,20,30,50);

// I can get the sum of array1 and array2 output.
$array_sum1 = array(10,50,50);


$array3 = array(4,4,4,6);
$array4 = array(10,20,30,50);

// I can get the sum of array3 and array4 output.
$array_sum2 = array(60,50);

How do I go about achieving this?

2 Answers2

2

You can use array_sum with array_map like below,

$array1     = [1, 2, 2, 3];
$array2     = [10, 20, 30, 50];
$array_sum1 = [];
foreach ($array1 as $key => $value) {
    $array_sum1[$value][] = $array2[$key];
}
$array_sum1 = array_map("array_sum", $array_sum1);
print_r($array_sum1);
$array3     = [4, 4, 4, 6];
$array4     = [10, 20, 30, 50];
$array_sum2 = [];
foreach ($array3 as $key => $value) {
    $array_sum2[$value][] = $array4[$key];
}
$array_sum2 = array_map("array_sum", $array_sum2);
print_r($array_sum2);die;

Demo

Output:-

Array
(
    [1] => 10
    [2] => 50
    [3] => 50
)
Array
(
    [4] => 60
    [6] => 50
)
Rahul
  • 18,271
  • 7
  • 41
  • 60
  • 1
    Your welcome. If you want to reset indexes of array use [array_values](https://www.php.net/manual/en/function.array-values.php). [Demo](https://3v4l.org/YCFEg) – Rahul Jan 22 '20 at 06:54
1

It is indirect to perform two iterations of your data to group & sum.

Use the "id" values as keys in your output array. If a given "id" is encountered for the first time, then save the "val" value to the "id"; after the first encounter, add the "val" to the "id".

Code: (Demo)

$ids = [1, 2, 2, 3];
$vals = [10, 20, 30, 50];

foreach ($ids as $index => $id) {
    if (!isset($result[$id])) {
        $result[$id] = $vals[$index];
    } else {
        $result[$id] += $vals[$index];
    }
}
var_export($result);

Output:

array (
  1 => 10,
  2 => 50,
  3 => 50,
)

Here are similar (near duplicate) answers:

mickmackusa
  • 43,625
  • 12
  • 83
  • 136