簡體   English   中英

PHP的MySQL購物車使用2D數組更新一個項目的數量

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

我正在構建的購物車似乎只是更新數組第一個元素的數量。 因此,例如,購物車中的第一件商品的數量為1,然后當我從產品頁面添加另一數量的2時,總數量變為3,這就是我想要的。 但是,如果我對其他項目重復這些步驟,則會將它們分別添加到數組中,而不是將它們分組在一起

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;
            }
        }
    }

誰能幫助我解決為什么第一個元素僅被更新?

您的問題是foreach循環中的else情況。 如果沒有,則檢查第一個項目,然后-當第一個項目不匹配時-否則激活並添加新項目。

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

您想要做的是檢查整個購物車,然后-如果找不到該文章,則將其添加到購物車中。 為此,我建議使用一個變量來檢查您是否在循環內找到了該條目。 為了獲得靈感,我在下面插入了代碼。 只需進行少量更改:添加find-variable並將其初始化(未找到),在if-case中將變量設置為found,並在退出foreach循環后檢查是否設置了變量(如果沒有,則進行設置) ,您肯定知道要將該商品添加到購物車中。

$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 }

我沒有測試過,但這可能會更簡單一些:

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;
    }
}

首先,問題和代碼似乎還不夠清楚,但是我會盡力給出我認為可能會有所幫助的建議(我會做一些假設)。

這些變量來自哪里?

$itemID, $quantity

假設它們要加入$_GET ,我想最好像這樣保存購物車信息:

$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]

完成此操作后,將購物車顯示/呈現給所有者就變得微不足道了。

祝好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM