I';我只是想从会话中删除一个项目[cart_item]


I'm just trying to remove the single item from a session[cart_item]

我使用了一个会话在没有数据库的页面中添加项目。这里我有一个问题,试图删除我的页面中的这个文件。这是我删除链接的代码。我过去常常通过标题变量来选择数据。

<a href="step3.php?action=remove&title=<?php echo $item["title"]; ?>" class="product-title">
    <span class="label label-warning pull-right">Remove</span>
</a>

我用开关盒来选择删除操作。

case "remove":
    if(!empty($_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
            if($_GET["title"] == $k)
                unset($_SESSION["cart_item"][$k]);              
            if(empty($_SESSION["cart_item"]))
                unset($_SESSION["cart_item"]);
        }
    }
break;

它完美地选择了标题变量。但是不执行移除动作。

在这里,我没有任何唯一的值来从会话中选择单个数据。。。也给出一些解决方案。。

您必须传递参数"code",否则"cart_item"应为空,但您的验证不应首先为空if条件if(!empty($_SESSION["cart_tem"])验证您的状况:

case "remove":
    if(!empty($_SESSION["cart_item"])) { //condition 1
        foreach($_SESSION["cart_item"] as $k => $v) {
                if($_GET["code"] == $k)
                    unset($_SESSION["cart_item"][$k]);              
                if(empty($_SESSION["cart_item"]))// condition 2 wont work 
                    unset($_SESSION["cart_item"]);
        }
    }
break;

if($_GET["code"] == $k)应该是if($_GET["title"] == $k)

您尚未通过链接传递$_GET["code"]。不应该是$_GET["title"] == $k吗?

在您的URL中,您传递的是actiontitle,而不是code

所以应该是

case "remove":
    if(!empty($_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
            if($_GET["title"] == $k)
                unset($_SESSION["cart_item"][$k]);              
            if(empty($_SESSION["cart_item"]))
                unset($_SESSION["cart_item"]);
        }
    }
break;