简体   繁体   中英

php mysql shopping cart updating quantity of an item using 2d array

The shopping cart I am building only seems to update the quantity for the first element of the array. So for example the first item in my shopping cart would have a quantity of 1 and then when I added another quantity of 2 from the products page the total then changes to 3 which is what I want. If I however repeat these steps for another item it will add them into the array separately rather than grouping them together

if(isset($_GET['add'])){
foreach ($_SESSION['cart'] as $key => $item){
            if ($item['id'] == $itemID) {

                $newQuan = $item['quantity'] + $quantity;

                unset($_SESSION['cart'][$key]);

                $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $newQuan);
                header('Location:xxx');//stops user contsanlty adding on refresh
                exit;
            }
            else{
                $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
                header('xxx');//stops user contsanlty adding on refresh
                exit;
            }
        }
    }

Can anyone help me out as to why the first element gets updated only ?

Your problem is the else-case in the foreach-loop. The very first item gets checked by the if and then - when the first item does not match - the else case activates and adds the new item.

else{
            $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
            header('xxx');//stops user contsanlty adding on refresh
            exit;
        }

What you would want to do, is to check the whole cart and then - if the article was not found - add it to the cart. For this I would suggest to use a variable for checking whether you found the entry inside the loop. For inspiration I inserted the code below. There are only minor changes needed: Add the found-variable and initialize it (to not found), set the variable to found in your if-case and check whether the variable is set after quitting the foreach-loop (which if it is not, you know for sure that you want to add the item to your cart).

$foundMyArticle = 0;

foreach ($_SESSION['cart'] as $key => $item){
        if ($item['id'] == $itemID) {
            $foundMyArticle = 1;
            ... THE OTHER CODE
} //end of the foreach

if($foundMyArticle == 0)
{ //COPY THE CODE FROM THE ELSE-CASE HERE }

I've not tested it, but this could be a little simpler:

if(isset($_GET['add']))
{
    if(!isset($_SESSION['cart'])) $_SESSION['cart'] = array();
    if(!isset($_SESSION['cart'][$itemID]))
    {
        $_SESSION['cart'][] = array('id' => $itemID, 'quantity' => $quantity);
    }
    else
    {
        $_SESSION['cart'][$itemID]['quantity'] += $quantity;
    }
}

Firstly, the question and the code don't seem really clear enough, but i'll try my best to give suggestions i think might help (I'll make some assumptions).

Where are these variables coming from?

$itemID, $quantity

Going on the assumption that they're coming in the $_GET , I'd say it would be better to save your cart information like so:

$itemCartIndex = strval($itemID);
//convert the integer item id to a string value -- or leave as string if already a string
$currentQuantity = (isset($_SESSION["cart"][$itemCartIndex]))? intval($_SESSION["cart"][$itemCartIndex]["quantity"]):0;
//set it by default if the index does not exist in the cart already
$currentQuantity += $quantity;
//update the quantity for this particular item
$_SESSION["cart"][$itemCartIndex] = array("quantity"=>$currentQuantity,...,"price"=>12.56);
//set up the index for this item -- this makes it easy to remove an item from the cart
//as easy as unset($_SESSION["cart"][$itemCartIndex]

With that done, displaying/presenting the cart back to the owner is trivial.

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM