frio80 Posted July 13, 2007 Share Posted July 13, 2007 I have an array: [letter] = An Array: [96-19205] = '1' [97-19205] = '2' [envel] = An Array: [96-19205] = '3' [97-19205] = '4' I would like the result to read: [papers] (the name isn't very important) [96-19205] = '4' [97-19205] = '6' Seems simple enough but just trying to figure out a more efficient method (using built-in array functions) rather than looping and looking for matches manually? Any thoughts? Thanks. Quote Link to comment Share on other sites More sharing options...
AbydosGater Posted July 13, 2007 Share Posted July 13, 2007 What exactly is it that you are asking? Quote Link to comment Share on other sites More sharing options...
frio80 Posted July 13, 2007 Author Share Posted July 13, 2007 Sorry for that lousy explanation. Let me try again. I would like to merge the arrays and add the values of the duplicates together. The array structure is: [<name>] [item#] = <quantity> ... So I have these two arrays named letter and evel [letter] = An Array: [96-19205] = '1' [97-19205] = '2' [98-12222] = '9' ... [envel] = An Array: [96-19205] = '3' [97-19205] = '4' [92-11231] = '3' I would like the resulting merged array to read: [papers] [96-19205] = '4' [97-19205] = '6' [92-11231] = '3' [98-12222] = '9' Thanks! Quote Link to comment Share on other sites More sharing options...
effigy Posted July 13, 2007 Share Posted July 13, 2007 <pre> <?php function sum_array_keys () { $result = array(); $arrays = func_get_args(); foreach ($arrays as $array) { foreach ($array as $k => $v) { $result[$k] += $v; } } return $result; } $letter = array( '96-19205' => 1, '97-19205' => 2, '98-12222' => 9, ); $envel = array( '96-19205' => 3, '97-19205' => 4, '92-11231' => 3, ); $result = sum_array_keys(&$letter, &$envel); print_r($result); ?> </pre> Quote Link to comment Share on other sites More sharing options...
Barand Posted July 13, 2007 Share Posted July 13, 2007 To avoid warning messages it's safer to if (isset($result[$k])) { $result[$k] += $v; } else $result[$k] = $v; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.