Jump to content

adding items in array


dadamssg87

Recommended Posts

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.