PHP Unset 正在重置我的会话数组

PHP Unset is resetting my Session Array

我在发送请求以从会话数组中删除特定产品时遇到问题。当结果 return 时,会话为空,并且在重置时它显然有多个值。这是代码。

    if (in_array($input_product_to_delete, $_SESSION['cart_items'])) {
        var_dump($_SESSION['cart_items']);
        var_dump($input_product_to_delete);
        unset($_SESSION['cart_items'],$input_product_to_delete);
        var_dump($_SESSION['cart_items']);
    }

正在输入条件并在我需要它时清除整个会话以仅清除一个对象。 这是转储的输出。

array(3) {
    [0]=> array(12) {
        [0]=> string(1) "4"
        ["ID"]=> string(1) "4"
        [1]=> string(11) "Razor Mouse"
        ["name"]=> string(11) "Razor Mouse"
        [2]=> string(46) "Lights Up with customizable keyboard shortcuts"
        ["description"]=> string(46) "Lights Up with customizable keyboard shortcuts"
        [3]=> string(2) "65"
        ["quantity"]=> string(2) "65"
        [4]=> string(5) "29.99"
        ["price"]=> string(5) "29.99"
        [5]=> string(8) "Hardware"
        ["type"]=> string(8) "Hardware"
    }
    [1]=> array(12) {
        [0]=> string(1) "5"
        ["ID"]=> string(1) "5"
        [1]=> string(13) "Nvidia GTX970"
        ["name"]=> string(13) "Nvidia GTX970"
        [2]=> string(70) "Extremely powerful graphics card for games that are graphics intensive"
        ["description"]=> string(70) "Extremely powerful graphics card for games that are graphics intensive"
        [3]=> string(2) "20"
        ["quantity"]=> string(2) "20"
        [4]=> string(6) "525.99"
        ["price"]=> string(6) "525.99"
        [5]=> string(8) "Hardware"
        ["type"]=> string(8) "Hardware"
    }
    [2]=> array(12) {
        [0]=> string(1) "9"
        ["ID"]=> string(1) "9"
        [1]=> string(4) "tewt"
        ["name"]=> string(4) "tewt"
        [2]=> string(4) "test"
        ["description"]=> string(4) "test"
        [3]=> string(3) "123"
        ["quantity"]=> string(3) "123"
        [4]=> string(1) "2"
        ["price"]=> string(1) "2"
        [5]=> string(8) "Hardware"
        ["type"]=> string(8) "Hardware"
    }
}

array(12) {
        [0]=> string(1) "9"
        ["ID"]=> string(1) "9"
        [1]=> string(4) "tewt"
        ["name"]=> string(4) "tewt"
        [2]=> string(4) "test"
        ["description"]=> string(4) "test"
        [3]=> string(3) "123"
        ["quantity"]=> string(3) "123"
        [4]=> string(1) "2"
        ["price"]=> string(1) "2"
        [5]=> string(8) "Hardware"
        ["type"]=> string(8) "Hardware"
    }

NULL 

取消设置后会话为空

我认为你的问题很简单。 Unset 接受很多你想要的参数。但是用逗号分隔你删除所有这些。在您的情况下,您删除了两个变量。

$_SESSION['cart_items']$input_product_to_delete

因此,如果您想删除数组中的一个元素,则必须将它们设置为数组数组,例如:

unset($_SESSION['cart_items'][$input_product_to_delete])

希望能解决您的问题。