LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   [PHP] Sum of a column by key (http://www.linuxquestions.org/questions/programming-9/%5Bphp%5D-sum-of-a-column-by-key-767257/)

kazuni 11-06-2009 04:01 AM

[PHP] Sum of a column by key
 
Hello everyone.

For example, I have an array which looks like below:

PHP Code:

$mycart

$mycart
[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;

$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;

$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;

$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8

I wanted to run a php function, or make one, that can make an array to sum up all the quantity by similar "product":

PHP Code:

$newcart

$newcart
[0]['product'] = 'ProductA';
$newcart[0]['quantity'] = 14;

$newcart[1]['product'] = 'ProductB';
$newcart[1]['quantity'] = 16

is there a function in php that does this?

graemef 11-07-2009 09:47 PM

I don't know of a PHP function that does what you want but it should be fairly simple to create your own. I would create a result array where the key is your product and the value is the sum of the quantity then just loop through the first array incrementing the total by the value in quantity. Thus you would have something like:

PHP Code:

foreach ($newcart as $product => $quantity)
   
$total[$product] += $quantity


kazuni 11-08-2009 11:48 PM

Quote:

Originally Posted by graemef (Post 3748757)
I don't know of a PHP function that does what you want but it should be fairly simple to create your own. I would create a result array where the key is your product and the value is the sum of the quantity then just loop through the first array incrementing the total by the value in quantity. Thus you would have something like:

PHP Code:

foreach ($newcart as $product => $quantity)
   
$total[$product] += $quantity


That's the ideal side; because I can just simply use a foreach loop to assign and add the quantity (as a value) to the product (as a key); however, I still can't think of an easy way.

anyone else got any ideas?

graemef 11-09-2009 12:43 AM

Maybe you need to be a little clearer about what you mean by "easy way".

What are the problems with the solution I suggested?
How wouldyou like the solution that I suggested be made easier?

Guttorm 11-09-2009 08:54 AM

Hi

PHP does have a lot of array functions, but they are mostly manipulating and getting information from arrays as key+value pairs. And since your arrays are not like that, you will need to loop thru the arrays with regular code.

PHP Code:

$totals = array();
foreach (
$mycart as $row) {
  
$product $row['product'];
  
$quantity $row['quantity'];
  
$totals[$product] += $quantity;
}

$newcart = array();
foreach (
$totals as $product => $quantity) {
  
$newcart[] = array('product' => $product'quantity' => $quantity);




All times are GMT -5. The time now is 02:39 PM.