user2530671 user2530671 - 3 months ago 9
PHP Question

Combining two PHP arrays with some conditional addition thrown in

I've got an unusual problem, but I'm fairly certain it's not impossible to solve.
Consider the two arrays below.

Array ( [0] => 1 [1] => 2 [2] => 2 )

Array ( [0] => 879 [1] => 482 [2] => 1616 )


I need to add the values in second array where the values in the first array are the same so that I would end up with...

Array ( [0] => 879 [1] => 2098 )


How might this be accomplished? Thanks in advance!

Answer

This isn't a full-proof way of completing this task, but it achieves the goal you desire. What's happening here is we're looping through your first array (the keys) and using the set values of these keys to add the values from the second array:

$new = array();
foreach($keys as $i => $key) {
    if(!isset($new[$key])) { $new[$key] = 0; }
    $new[$key] += $vals[$i];
}

Example/Demo

Notes

  • $keys being your first array: $keys = array(1, 2, 2);
  • $vals being your second array: array (879, 482, 1616);

As I stated, this isn't full-proof. You will need to modify it to ensure integrity, but it is a start that shows the flow of how you can go about doing what you require.

Comments