2016-05-27 70 views
0

想要將鍵和值附加到已創建的會話。將陣列鍵值附加到會話數組

if (!isset($_SESSION['cart'])) { 

       $bag = array(
         "sessionId" => session_id(), 
         "productId" => $productId, 
         "size"  => $productSize, 
         "quantity" => $productQuantity 
        ); 

       $_SESSION['cart'] = $bag; 

      } else { 

       $_SESSION['cart']['sessionId'] = session_id(); 
       $_SESSION['cart']['productId'] = $productId; 
       $_SESSION['cart']['size'] = $productSize; 
       $_SESSION['cart']['quantity'] = $productQuantity; 

      } 

如果會話已經被創建,然後使用它的關鍵字將新變量追加到會話中。

回答

0

$_SESSION['cart']應該是一個項目數組,而不是您寫的一個項目。每個項目將是一個單獨的關聯數組,您將其推送到購物車陣列上。

if (!isset($_SESSION['cart'])) { 
    $_SESSION['cart'] = array(); 
} 
$bag = array(
    "sessionId" => session_id(), 
    "productId" => $productId, 
    "size"  => $productSize, 
    "quantity" => $productQuantity 
); 
$_SESSION['cart'][] = $bag; 
+0

太好了,謝謝。將標記! – Zack1101