0

I have 2 Arrays, I need To Sum Array 2 values and then associate them back with array 1 value

$records_array = array('314','314','500','2100','2100','3210','2100');
$quantities_array = array('2010','1','2250','1000','1000','950','1000');

The results I need for comparative reasons

  • Record: 314 Qty = 2011 (key 0, 1 are added together)
  • Record: 500 Qty = 2250 (key 2 only)
  • Record: 2100 Qty = 3000 (key 3, 4, 6 are added together)
  • Record: 3210 Qty 950 (key 5 value)

What I do know is the array keys 0,1,2,3,4,5,6 will match record to quantity they're just in 2 different arrays.

**Just edited, find all duplicate values in records_array and add the same keys in quantities_array, then return the sum of quantities array for each records array value **

What is the best way to iterate through the arrays and return these type of results?

Thank you

6
  • Sorry, but your question doesn't make any sense. Can you provide the expected output so we may be able to understand it better? Commented Feb 27, 2014 at 13:35
  • I really try hard to uderstand your question, but it make no sense. What you want to do? sum up the array? just compare? huh? Commented Feb 27, 2014 at 13:38
  • Have you tried iterating over the arrays? Assuming no problem conditions (e.g. different sizes), a single for one-liner would do it. Or you could do it with a call to array_map. Commented Feb 27, 2014 at 13:39
  • Just edited, find all duplicate values in records_array and add the same keys in quantities_array Commented Feb 27, 2014 at 13:40
  • If you want to sum up array, just use array_sum( $records_array ). Second your array was write in a wrong way, just correct it -> $records_array = array( '314','500','2100','2100','3210','2100' ); Commented Feb 27, 2014 at 13:40

2 Answers 2

1
<?php     
    $records_array = array('314','314','500','2100','2100','3210','2100');
    $quantities_array = array('2010','1','2250','1000','1000','950','1000');
    $new_array = array();
    foreach ($records_array as $record_position => $new_array_key){
        $new_array[$new_array_key] += $quantities_array[$record_position];
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

This unexplained answer generates Warnings/Notices and should not be used by researchers.
0
foreach ($records_array as $key => $val)
  $result[$val] += $quantities_array[$key];

Like this maybe?

1 Comment

This unexplained answer generates Warnings/Notices and should not be used by researchers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.