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. Link to comment https://forums.phpfreaks.com/topic/59836-fun-with-arrays/ 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? Link to comment https://forums.phpfreaks.com/topic/59836-fun-with-arrays/#findComment-297547 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! Link to comment https://forums.phpfreaks.com/topic/59836-fun-with-arrays/#findComment-297552 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> Link to comment https://forums.phpfreaks.com/topic/59836-fun-with-arrays/#findComment-297554 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; Link to comment https://forums.phpfreaks.com/topic/59836-fun-with-arrays/#findComment-297566 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.