2012-04-05 103 views
0

當我如執行此下面的代碼:cart.php P = 1個&行動=添加

<?php 
session_start(); 

if (isset($_GET['p']) && isset($_GET['action'])) { 
$p_id = (int)$_GET['p']; 
$action = $_GET['action']; 

switch($action) { 

    case "add": 
     $_SESSION['cart'][$p_id]++; 
     echo $_SESSION['cart'][$p_id];//for debug 
    break; 

    case "remove": 
     $_SESSION['cart'][$p_id]--; 
     echo $_SESSION['cart'][$p_id]; 
     if($_SESSION['cart'][$p_id] == 0) unset($_SESSION['cart'][$p_id]); 
    break; 

    case "empty": 
     unset($_SESSION['cart']); 
    break; 
} 
} 
?> 

我得到以下錯誤:

Notice: Undefined offset: 1 in cart.php on line 11 

哪有我正確地配置PHP $ _SESSION?我

回答

3

更改此:

$_SESSION['cart'][$p_id]++ 

到:

$_SESSION['cart'][$p_id] = 1 + (isset($_SESSION['cart'][$p_id]) ? $_SESSION['cart'][$p_id] : 0); 

所以,你不嘗試你的陣列中增加一個不存在的元素。

+0

非常聰明和明確的答案,我已經嘗試了很多issets ...非常感謝你! – CBuzatu 2012-04-05 04:20:05

+0

但在刪除代碼的情況下是好的? – CBuzatu 2012-04-05 04:20:59

+0

@ user1274699刪除也可以使用isset。就像'if(!isset($ _ SESSION ['cart'] [$ p_id]))break;'會導致它退出switch語句,因爲沒有設置(因爲沒有東西可以刪除)。您可能想要添加額外的錯誤處理 – Paulpro 2012-04-05 04:24:31