bachx Posted September 2, 2009 Share Posted September 2, 2009 I'm looking for a way to remove duplicate values from the following example and add up their sum in a way like this: Array ( [0] => Array ( [name] => CAR [amount] => 1000 ) [1] => Array ( [name] => BUS [amount] => 500 ) [2] => Array ( [name] => CAR [amount] => 750 ) ) To: Array ( [0] => Array ( [name] => CAR [amount] => 1750 ) [1] => Array ( [name] => BUS [amount] => 500 ) ) Any ideas? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/172800-removing-duplicates-and-adding-up-their-values-in-multidimentional-arrays/ Share on other sites More sharing options...
ignace Posted September 2, 2009 Share Posted September 2, 2009 Possibly you got this from a db and IMO it would then be better to handle this in your query: SELECT name, sum(amount) sum_amount FROM table GROUP BY name Quote Link to comment https://forums.phpfreaks.com/topic/172800-removing-duplicates-and-adding-up-their-values-in-multidimentional-arrays/#findComment-910787 Share on other sites More sharing options...
methomps Posted September 2, 2009 Share Posted September 2, 2009 <?php $array1 = array(array('name'=>'CAR', 'amount'=>1000), array('name'=>'BUS', 'amount'=>500), array('name'=>'CAR', 'amount'=>750)); $array2 = array(); foreach($array1 as $miniarray) { if(isset($array2[$miniarray['name']])) { $array2[$miniarray['name']] += $miniarray['amount']; } else { $array2[$miniarray['name']] = $miniarray['amount']; } } //if it has to be in the format you specified $array1 = array(); foreach($array2 as $key=>$value) { $array1[] = array($key=>$value); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/172800-removing-duplicates-and-adding-up-their-values-in-multidimentional-arrays/#findComment-910788 Share on other sites More sharing options...
methomps Posted September 2, 2009 Share Posted September 2, 2009 Correction, the last part of that should be: //if it has to be in the format you specified $array1 = array(); foreach($array2 as $key=>$value) { $array1[] = array('name'=> $key, 'amount'=> $value); } Quote Link to comment https://forums.phpfreaks.com/topic/172800-removing-duplicates-and-adding-up-their-values-in-multidimentional-arrays/#findComment-910794 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.