如何增加购物车中的物品数量

时间:2019-07-04 12:33:02

标签: php session 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;
    }     
}

2 个答案:

答案 0 :(得分:1)

您可以使用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"];
    }
}
...

答案 1 :(得分:0)

您的程序逻辑正确,只需将其更新为:

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