从CakePHP中的会话中删除数组项

时间:2014-03-04 04:50:45

标签: arrays session cakephp

我已经在会话中添加了一个数组(购物车)。现在要从购物车中删除一个项目,我尝试了这个逻辑。购物车工作正常,我可以在我的页面上看到购物车中的所有商品。删除逻辑不会给我任何错误,但也不会从会话中删除该项。

我做错了什么?

function addToCart(){

    $this->layout = false;
    $this->render(false);

    $cart = array();

    $tempcart = unserialize($this->Session->read("cart")); 

    if(isset($tempcart)){
        $cart = $tempcart;
    }

    $productId = $this->request->data("id");

    if(!$this->existsInCart($cart, $productId)){

        $cart[] = array("productId" => $productId, "createdAt" => date());

        $this->Session->write("cart", serialize($cart));

        echo "added";
    }
    else
        echo "duplicate";
}


function removeFromCart(){

    $this->layout = false;
    $this->render(false);

    $cart = array();

    $tempcart = unserialize($this->Session->read("cart"));

    if(isset($tempcart)){
        $cart = $tempcart;
    }

    $productId = $this->request->data("productId");

    for($i=0;$i<count($cart);$i++){

        $cartItem = $cart[$i];   //  an array

        if($cartItem["productId"]==$productId)
            unset($cart[$i]);
    }

    $this->Session->write("cart", serialize($cart));

    echo "removed";
}

3 个答案:

答案 0 :(得分:1)

$productId = $this->request->data("productId");

您确定要写“productId”而不是“id”吗?

您似乎在添加到购物车期间在请求中发送了“id”,可能您在删除时也是这样做。

此外,您已将购物车保存在$cart,因此您需要序列化$cart而不是$newcart

因此,您从购物车代码中移除的内容将变为:

function removeFromCart(){

    $this->layout = false;
    $this->render(false);

    $cart = array();

    $tempcart = unserialize($this->Session->read("cart"));

    if(isset($tempcart)){
        $cart = $tempcart;
    }

    $productId = $this->request->data("id");

    for($i=0;$i<count($cart);$i++){

        $cartItem = $cart[$i];   //  an array

        if($cartItem["productId"]==$productId)
            unset($cart[$i]);
    }

    $this->Session->write("cart", serialize($cart));

    echo "removed";
}

答案 1 :(得分:1)

您没有使用正确的值更新会话

function removeFromCart() {
    $this->layout = false;
    $this->render(false);

    $productId = $this->request->data("productId");

    // make sure this is the value you need
    debug($productId);

    $tempCart = unserialize($this->Session->read("cart"));
    if (!empty($tempCart)) {
        for ($i=0; $i<count($tempCart); $i++) {
            if ($tempCart[$i]["productId"] == $productId) {
                unset($tempCart[$i]);
            }
        }
        $this->Session->write("cart", serialize($tempCart));
    }

    echo "removed";
}

答案 2 :(得分:1)

为什么你不使用会话组件的delete()功能?

$this->Session->delete('cart');
相关问题