簡體   English   中英

如何增加購物車中的物品數量

[英]How to increase Items Quantity in Cart

我想增加產品的數量,當我多次單擊“添加到購物車”,但我沒有增加數量時,保持不變,有人幫助我解決了這個問題。 我在空白其他部分中編碼什么

if(isset($_POST["submit1"]))
{
    if(isset($_SESSION["shopping_cart"]))
    {
        $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
        if(!in_array($_GET["product_id"], $item_array_id))
        {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'item_id'           =>  $_GET["product_id"],
                'item_name'         =>  $_POST["hidden_name"],
                'item_price'        =>  $_POST["hidden_price"],
                'item_quantity'     =>  $_POST["quantity"],
               'item_image'     =>  $_POST["hidden_image"],

            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        }
        else
        {




        }
    }
    else
    {
        $item_array = array(
            'item_id'           =>  $_GET["product_id"],
            'item_name'         =>  $_POST["hidden_name"],
            'item_price'        =>  $_POST["hidden_price"],
            'item_quantity'     =>  $_POST["quantity"],
            'item_image'        =>  $_POST["hidden_image"],

        );
        $_SESSION["shopping_cart"][0] = $item_array;
    }     
}

您可以使用array_search獲取項目的鍵,如下所示:

// look for 'item_id' with the value of $_GET["product_id"] inside of the cart
$itemIds = array_column( $_SESSION["shopping_cart"], "item_id" );
$key = array_search( $_GET["product_id"], $itemIds );

然后您可以通過執行以下操作輕松更新該商品的數量:

...
if (isset($_SESSION["shopping_cart"]))
{
    // look for 'item_id' with the value of $_GET["product_id"] inside of the cart
    $itemIds = array_column( $_SESSION["shopping_cart"], "item_id" );
    $key = array_search( $_GET["product_id"], $itemIds );

    if ( $key === false )
    {
        $item_array = array(
            'item_id'           =>  $_GET["product_id"],
            'item_name'         =>  $_POST["hidden_name"],
            'item_price'        =>  $_POST["hidden_price"],
            'item_quantity'     =>  $_POST["quantity"],
            'item_image'        =>  $_POST["hidden_image"],

        );
        $_SESSION["shopping_cart"][] = $item_array;
    }
    else
    {
        // if quantity is invalid do something, else
        $_SESSION["shopping_cart"][$key]["item_quantity"] += $_POST["quantity"];
    }
}
...

您的程序邏輯是正確的,只需將其更新為:

$count++;
$_SESSION["shopping_cart"][$count] = $item_array;

暫無
暫無

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

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