AndyPSV Posted January 31, 2011 Share Posted January 31, 2011 array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 1 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 2 => array ( 'id' => '2', 't' => 'Automotive', ), ) how to sum it, to get: array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', 'cnt' => '2' ), 1 => array ( 'id' => '2', 't' => 'Automotive', 'cnt' => '1' ), ) Quote Link to comment https://forums.phpfreaks.com/topic/226279-multidimensional-array-summing-same-keys/ Share on other sites More sharing options...
AbraCadaver Posted January 31, 2011 Share Posted January 31, 2011 Maybe overly complex but I have a cold and my brain is fuzzy: $new_array = array(); foreach($array as $value) { if(isset($new_array[$value['id']])) { $new_array[$value['id']]['cnt']++; } else { $new_array[$value['id']] = $value; $new_array[$value['id']]['cnt'] = 1; } } Quote Link to comment https://forums.phpfreaks.com/topic/226279-multidimensional-array-summing-same-keys/#findComment-1168073 Share on other sites More sharing options...
AbraCadaver Posted January 31, 2011 Share Posted January 31, 2011 No simpler, but shorter :-\ foreach($array as $value) { if(!isset($new_array[$value['id']])) { $new_array[$value['id']] = $value; $new_array[$value['id']]['cnt'] = 0; } $new_array[$value['id']]['cnt']++; } Quote Link to comment https://forums.phpfreaks.com/topic/226279-multidimensional-array-summing-same-keys/#findComment-1168076 Share on other sites More sharing options...
ManiacDan Posted January 31, 2011 Share Posted January 31, 2011 AbraCadaver is doing it the way I would. There may be a faster way, but this is good enough. -Dan Quote Link to comment https://forums.phpfreaks.com/topic/226279-multidimensional-array-summing-same-keys/#findComment-1168088 Share on other sites More sharing options...
AndyPSV Posted January 31, 2011 Author Share Posted January 31, 2011 Thank you very much for your help. I'm going sleep now, you've helped a lot. Quote Link to comment https://forums.phpfreaks.com/topic/226279-multidimensional-array-summing-same-keys/#findComment-1168091 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.