Forum Moderators: coopster

Message Too Old, No Replies

Help summing specific values in a cookie array

         

MrL8Knight

4:03 am on Mar 8, 2006 (gmt 0)

10+ Year Member



I am building a simple shopping cart and I am having problems trying to add the costs of the items to generate a total cost. I am new at this so forgive me if my technical verbiage isn’t the greatest!

I am trying to sum specific values in my arrays (or the price portions of the arrays). I have tried every imaginable way with the array_sum command and nothing has worked for me!

Here is what my cookie information looks like after I put 2 test items into the cart that cost 18.00 each.

Array ( [0] => 21 [1] => test1 [2] => 12 [3] => 12 [4] => 1 [5] => Please select [6] => Please select [7] => Please select [8] => [9] => 18.00 ) Array ( [0] => 22 [1] => test2 [2] => 12 [3] => 12 [4] => 1 [5] => Please select [6] => Please select [7] => Please select [8] => [9] => 18.00 )

Arrays 21 and 22 both contain items with a price of 18.00
I am trying to add both of the [9] fields (18.00) to come up with a total cost

Here is the code I am using to try to add the price of both items:

<?

foreach ($_COOKIE[mycookie] as $valueq) {

$value3 = unserialize(stripslashes($valueq));
}
echo "Total Cost = " . array_sum($value3) . "\n";

?>

When I load this page, it comes up with a total of 65 instead of 36 (18+18)

I’m thinking the problem is that I am summing all the values when I just need to sum the values of the [9] field which contains the prices.

Any help would be greatly appreciated!

MrL8Knight

MrL8Knight

10:37 am on Mar 8, 2006 (gmt 0)

10+ Year Member



I just got my hands on the script to make it work properly from the Guru Banfa
Here it is

<?

$total = 0;

foreach ($_COOKIE[mycookie] as $valueq)
{
$value3 = unserialize(stripslashes($valueq));
$total += $value3[9];
}

echo "Total Cost = " . $total . "\n";

?>

coopster

1:11 pm on Mar 8, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, MrL8Knight.

Glad you got it sorted. You may also want to quote that $_COOKIE index.

foreach ($_COOKIE['mycookie'] as $valueq)

The PHP manual pages on Arrays [php.net] explains why.