greenApple Posted March 23, 2011 Share Posted March 23, 2011 I am populating an array with product details, each product has a price. I have tried to create a loop to add the price of each product to create a grandtotal but I am having difficulties $total=$item['qty'] * $item['price'];//multiples the quantity by price to get total price while ($total) { $grandTotal = $grandTotal + $total; } echo $grandTotal; Any ideas? Link to comment Share on other sites More sharing options...
birbal Posted March 23, 2011 Share Posted March 23, 2011 how is your $item array structure? how the data of $item are represented? showing us the full code will be more helpfull i think. Link to comment Share on other sites More sharing options...
greenApple Posted March 23, 2011 Author Share Posted March 23, 2011 This is the array code if (!isset($_SESSION['SHOPPING_CART'])){ $_SESSION['SHOPPING_CART'] = array(); }//Add an item only if we have the threee required pices of information: name, price, qtyif (isset($_GET['add']) && isset($_GET['price']) && isset($_GET['qty'])){ //Adding an Item //Store it in a Array $ITEM = array( //Item name 'name' => $_GET['add'], //Item Price 'price' => $_GET['price'], //Qty wanted of item 'qty' => $_GET['qty'] ); //Add this item to the shopping cart $_SESSION['SHOPPING_CART'][] = $ITEM; //Clear the URL variables header('Location: ' . $_SERVER['PHP_SELF']);} Link to comment Share on other sites More sharing options...
birbal Posted March 23, 2011 Share Posted March 23, 2011 if i understand your purpose... you are going to calculate multiple items total price ($grandtotal). i think you need a 2D array..to do so. assuming grandtotal means the whole total price of all item.eg. $items[0]=array('price'=>10,'quantity'=>30);$items[1]=array('price'=>12,'quantity'=>50);where $items[0] is a item. which has fixed price and quantity.and you want to calculate total of each item. right?then you should use foreach loop (foreach is good to iterate through a array) iterate through $items to get each $item take price and quantity of each item, calculate the total of item. and add each total price of each item to manupulate grandtotal.. Link to comment Share on other sites More sharing options...
ShadowMage Posted March 23, 2011 Share Posted March 23, 2011 OP already has a 2d array stored in the $_SESSION. A foreach loop should do the trick: $grandTotal = 0;foreach ($_SESSION['SHOPPING_CART'] as $Item) { $grandTotal += $Item['quantity']*$Item['price'];} Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.