2017-03-13 57 views
2

我在使用自定義函數在PHP的$ _SESSION變量中添加項目時遇到了問題。 所以......我想,當我打電話陣列覆蓋的功能與每一次這樣的通過函數寫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 
     ) 
) 
+0

'$ _SESSION [「cart」] [implode(「 - 」,$ combination)]'只向session [cart]添加一個數組。你如何結束3項? – apokryfos

+0

@apokryfos通過在購物車中添加多個產品 – Alex

回答

1

要調用集,您已寫入到覆蓋整個數組值。

你要麼需要先得到它,增加你的價值,然後設置:

$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); 

或添加新的方法來處理2維數組:

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 
)); 
+0

謝謝先生!這就是我想要的。謝謝! – Alex