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
https://forums.phpfreaks.com/topic/249333-adding-items-in-array/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.