dadamssg87 Posted October 18, 2011 Share Posted October 18, 2011 I have an array of products. The array has an ID and price. I'd like to know the most efficient way of adding up all the same ID fields in the array. <?php $items[] = array( 'id' => 1, 'price' => 5.99, ); $items[] = array( 'id' => 2, 'price' => 1.99, ); $items[] = array( 'id' => 3, 'price' => 2.40, ); $items[] = array( 'id' => 2, 'price' => 6.99, ); $items[] = array( 'id' => 4, 'price' => 8, ); $items[] = array( 'id' => 2, 'price' => 3, ); $items[] = array( 'id' => 3, 'price' => 1, ); function add_like_items($items) { //manipulation return $sums; } //$sums would be an array like //$sum[1] = 5.99 //$sum[2] = 11.98 //$sum[3] = 3.40 //$sum[4] = 8 ?> Anybody have suggestions on the best way to go about doing this? Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted October 18, 2011 Share Posted October 18, 2011 Not tested: foreach($items as $item) { if(isset($sums[$item['id']])) { $sums[$item['id']] += $item['price']; } else { $sums[$item['id']] = $item['price']; } } Quote Link to comment Share on other sites More sharing options...
dadamssg87 Posted October 18, 2011 Author Share Posted October 18, 2011 works great. Thanks a lot. I would've wrote something way more complicated than need be. I appreciate it! Quote Link to comment Share on other sites More sharing options...
xyph Posted October 18, 2011 Share Posted October 18, 2011 If you want to go for pure efficiency, I think it would be hard to beat this <?php $items[] = array( 'id' => 1, 'price' => 5.99, ); $items[] = array( 'id' => 2, 'price' => 1.99, ); $items[] = array( 'id' => 3, 'price' => 2.40, ); $items[] = array( 'id' => 2, 'price' => 6.99, ); $items[] = array( 'id' => 4, 'price' => 8, ); $items[] = array( 'id' => 2, 'price' => 3, ); $items[] = array( 'id' => 3, 'price' => 1, ); print_r( subkey_sum($items) ); function subkey_sum( $array ) { $sum = array(); for( $i=0,$l=count($array); $i<$l; $i++ ) { $sum[ $array[$i]['id'] ] = isset($sum[$array[$i]['id']]) ? $sum[ $array[$i]['id'] ] + $array[$i]['price'] : $array[$i]['price']; } return $sum; } ?> I'm quite sure my method is slightly faster and uses less memory than AbraCadaver's. His is slightly cleaner. You did ask for the most efficient solution though. 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.