通过功能写入SESSION

时间:2017-03-13 14:22:33

标签: php

我在使用自定义函数在PHP的$ _SESSION变量中添加项目时遇到问题。 所以...我想用这样的函数编写会话

public function set($key, $value) {
    $_SESSION[$key] = $value;
}

但每当我调用该函数时,数组都会被覆盖

//$combination = "1-10"; > 1 = product_id | 10 = option_id

$this->session->set("cart", array(implode("-", $combination) => array(
    "product_id" => $combination["product_id"],
    "variant_id" => $combination["variant_id"],
    "quantity" => 1
)));

输出

[cart] => Array
    (
        [1-30] => Array
            (
                [product_id] => 1
                [variant_id] => 30
                [quantity] => 1
            )
    )
)

这是正常的

$_SESSION["cart"][implode("-", $combination)] = array(
    "product_id" => $combination["product_id"],
    "variant_id" => $combination["variant_id"],
    "quantity" => 1
);

输出

[cart] => Array
(
    [1-30] => Array
        (
            [product_id] => 1
            [variant_id] => 30
            [quantity] => 1
        )
    [1-29] => Array
        (
            [product_id] => 1
            [variant_id] => 29
            [quantity] => 1
        )
    [1-28] => Array
        (
            [product_id] => 1
            [variant_id] => 28
            [quantity] => 1
        )
)

1 个答案:

答案 0 :(得分:1)

您正在调用set,您已编写该值以覆盖整个数组值。

您需要先获取它,添加您的值,然后设置:

$cart  = $this->session->get("cart");
$cart[implode("-", $combination)] = array(
    "product_id" => $combination["product_id"],
    "variant_id" => $combination["variant_id"],
    "quantity" => 1
);
$this->session->set("cart", $cart);

或添加一个新方法来处理二维数组:

public function merge($key,$value){
    $_SESSION[$key]=array_merge($_SESSION[$key],$value);
}

$this->session->merge("cart", array(implode("-", $combination) => array(
    "product_id" => $combination["product_id"],
    "variant_id" => $combination["variant_id"],
    "quantity" => 1
)));

public function setInArray($key, $subKey, $value){
    $_SESSION[$key][$subKey]=$value;
}

$this->session->setInArray("cart", implode("-", $combination), array(
    "product_id" => $combination["product_id"],
    "variant_id" => $combination["variant_id"],
    "quantity" => 1
));