-1

I have the following array:

[ 
    ['id' => 1, 'uid' => 50, 'sum1' => 1, 'sum2' => 2],
    ['id' => 2, 'uid' => 50, 'sum1' => 2, 'sum2' => 4],
    ['id' => 3, 'uid' => 51, 'sum1' => 3, 'sum2' => 5],
]

As you can see, on some of those indexes, [uid] is the same. The length and data of the array is dynamic.

What I need to do is merge the indexes that have the same value for [uid] and sum the values of the non-identifying keys.

Desired result:

[
    ['id' => 2, 'uid' => 50, 'sum1' => 3, 'sum2' => 6],
    ['id' => 3, 'uid' => 51, 'sum1' => 3, 'sum2' => 5],
]
4
  • Does this answer your question? How to sum all column values in multi-dimensional array? Commented Mar 31, 2021 at 21:31
  • Create a new array, iterate over the original one, for each item check if an object having same uid is present (using array_column and array_search)... if present increment values, otherwise append. Not difficult. Commented Mar 31, 2021 at 21:31
  • Actually, B001, it dosen't because inthat example are all idexes to be summed up or in my case, i need to sum only the matching keys. Commented Mar 31, 2021 at 21:56
  • @SalmanA, that is a good idea. i'll try to implemet that. thanks. Commented Mar 31, 2021 at 21:57

3 Answers 3

1

You can do it like this way,

<?php
$mainArray = [ 
    0 => Array
    (
        'id' => 1,
        'uid' => 50,
        'sum1' => 1,
        'sum2' => 2
    ),
    1 => Array
    (
        'id' => 2,
        'uid' => 50,
        'sum1' => 2,
        'sum2' => 4
    ),
    2 => Array
    (
        'id' => 3,
        'uid' => 51,
        'sum1' => 3,
        'sum2' => 5
    )
];
$newArray=[];
foreach ($mainArray as $value) {
    if(!array_key_exists($value['uid'], $newArray)){
        // Store first time
        $newArray[$value['uid']] = $value;
    }else{
        // Already exist, then sum and replace it
        $newArray[$value['uid']]['id'] = $value['id'];
        $newArray[$value['uid']]['sum1'] += $value['sum1'];// Sum with previous value
        $newArray[$value['uid']]['sum2'] += $value['sum2'];// Sum with previous value
    }
}
$newArray = array_values($newArray);// Reset indexes, Start the array index with zero
print_r($newArray);// To see the output

Output:


Array
(
    [0] => Array
        (
            [id] => 2
            [uid] => 50
            [sum1] => 3
            [sum2] => 6
        )

    [1] => Array
        (
            [id] => 3
            [uid] => 51
            [sum1] => 3
            [sum2] => 5
        )
)

Sign up to request clarification or add additional context in comments.

Comments

0

I think you are correct. Actually, i solved the problem using something similar:

$sumArray = Array();
foreach ($array1 as $item){

        if(isset($sumArray[$item['uid']])){          
          $sumArray[$item['idPartener']]['sum1'] += $item['sum1'];
          $sumArray[$item['idPartener']]['sum2'] += $item['sum2'];

        }else{          
          $sumArray[$item['uid']] = Array(
            'id' => $item['id'],             
            'sum1' => $item['sum1'],
            'sum2' => $item['sum2'] ,
          );
        }

    }

Thanks all for your help!

Comments

0

To avoid needing to re-index the array after grouping, push a reference into the result array every time a unique uid value is encountered. That reference should carry the whole row as the base value. If the same uid is encountered again, add the sum1 and sum2 values to the reference's respective column values.

Code: (Demo)

$result = [];
foreach ($array as $row) {
    if (!isset($ref[$row['uid']])) {
        $ref[$row['uid']] = $row;
        $result[] =& $ref[$row['uid']];
        continue;
    }
    $ref[$row['uid']]['sum1'] += $row['sum1'];
    $ref[$row['uid']]['sum2'] += $row['sum2'];
}
var_export($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.