简体   繁体   English

在php中完成删除购物车商品时,会话数组未取消设置

[英]Session array is not unsetting when remove cart item is done in php

I written this code for unsetting the session array when remove cart item button is clicked: 我编写了这段代码,用于在单击“删除购物车项目”按钮时取消设置会话数组:

$i=0;
    foreach ($_SESSION["items"] as $cart_itm) //loop through session array var
    {           
    //echo count($_SESSION['items']);
        if($cart_itm["id"] == $item_Id){ //item id is equal
            if(count($_SESSION['items']) == 1)
            {
            //echo "count1";
                unset($_SESSION['items']);
                $empty = 'Y';
            }
            else
            {

            echo $i."--";
            echo $cart_itm["id"];
            echo "------";
                unset($_SESSION['items'][$i]);
                $empty = 'N';

            }
        }
        $i++;
     }

But it unsets the first row in Shopping cart table when remove cart item is clicked for first.But when remove cart item is clicked for second row, the array is not unset and item is not removed from cart. 但是,当先单击删除购物车商品时,它将取消购物车表中的第一行。但是,当单击删除购物车商品作为第二行时,则不会取消设置数组,也不会从购物车中删除商品。 Also, if I click the remove cart item for 3rd row, the second row is deleted instead of 3rd row. 另外,如果我单击第三行的“删除购物车”项目,第二行将被删除,而不是第三行。

Please let me know why this is happening. 请让我知道为什么会这样。

How it make a sense just to use foreach for unset $_SESSION["items"], 仅使用foreach来设置未设置的$ _SESSION [“ items”]有何意义,

What's the problem , if you will do like this: 这是什么问题,如果您要这样做:

 if(isset($_SESSION["items"]) && count($_SESSION["items"])>0)
 unset($_SESSION["items"]);

Thanks 谢谢

Try this approach 试试这个方法

for($i=0; $i < count($_SESSION["items"]); $i++)
{           
    if($_SESSION["items"][$i] == $item_Id){
        unset($_SESSION['items'][$i]);
        break;
    }
}

let me know if I missed something. 让我知道是否错过了什么。

This problem is may be due to incorrect key is passed by your loop to unset desired session value. 此问题可能是由于循环传递的密钥不正确而未设置所需的会话值所致。 Instead of using $i++ approach , you can simply use KEY => VALUE PAIR. 除了使用$ i ++方法,您还可以简单地使用KEY => VALUE PAIR。

Example: 例:

foreach ($_SESSION["items"] as $sessionKey=>$cart_itm) //loop through session array var
{           
    //echo count($_SESSION['items']);
    if($cart_itm["id"] == $item_Id){ //item id is equal
        if(count($_SESSION['items']) == 1)
        {
            //echo "count1";
            unset($_SESSION['items']);
            $empty = 'Y';
        }
        else
        {

            echo $sessionKey."--";
            echo $cart_itm["id"];
            echo "------";
            unset($_SESSION['items'][$sessionKey]);
            $empty = 'N';

        }
    }        
 }

Try this approach , it may be helpful. 试试这种方法,可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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