2017-10-06 52 views
-2

我如何添加1到數量如果它不是新條目,並且如果它是新項目,它只會將項目添加到session['cart'],我試圖將其添加到session['cart']['qty']如果In_array是真的,使用PHP

if (!isset($_SESSION['cart'])) { 
    $item = array('pid' => $p['productID'], 
        'qty' => 1 
       ); 
    $_SESSION['cart'][0] = $item; 
} else { 
    $item_id = array_column($_SESSION['cart'], "pid"); 

    if (in_array($p['productID'], $item_id)) { 
     $to_update = 'qty'; 
     $new_qty = 5; 
     $base = $_SESSION['cart']['pid']['qty']; 
    } else { 
     $count = count($_SESSION['cart']); 
     $item = array('pid' => $p['productID'], 
         'qty' => 1 
        ); 
     $_SESSION['cart'][$count] = $item; 
    } 
} 
+0

實際上會發生什麼? – SteveFest

回答

0

你可以使用$ PID作爲唯一指標來跟蹤

$pid=$p['productID']; 
if(!isset($_SESSION['cart'][$pid])){ 
    $item = array(
     'pid' => $pid, 
     'qty' => 1 
    ); 
    $_SESSION['cart'][$pid] = $item; 
}else{ 
    /* 
    * add 1 qty 
    */ 
    if(isset($_SESSION['cart'][$pid])) { 
     $_SESSION['cart'][$pid]['qty']= ($_SESSION['cart'][$pid]['qty'] +1); 
    } 
} 

你也CAL使用類似的減少量。

0

您沒有更改會話變量。試試這個:

if (!isset($_SESSION['cart'])) { 
    $item = array('pid' => $p['productID'], 
        'qty' => 1 
       ); 
    $_SESSION['cart'][0] = $item; 
} else { 
    $item_id = array_column($_SESSION['cart'], "pid"); 

    if (in_array($p['productID'], $item_id)) { 
     $new_qty = 5; 
     $_SESSION['cart'][$p['productID']]['qty'] += $new_qty; 
    } else { 
     $count = count($_SESSION['cart']); 
     $item = array('pid' => $p['productID'], 
         'qty' => 1 
        ); 
     $_SESSION['cart'][$count] = $item; 
    } 
} 

這條線在這裏沒有意義。

$base = $_SESSION['cart']['pid']['qty']; 

多維數組不能像那樣工作。
您正在嘗試訪問陣列$_SESSION['cart']['pid']中的密鑰qty,但該項不存在。這兩個鍵是兄弟姐妹。

+0

感謝這些答案,但還有另一個問題,如果我選擇購買2個產品,並嘗試增加1個產品的數量我已經添加到我的購物車它不會合並它會創建新的行 –

+0

@EcnerolOdirrag好吧,當然,作爲只要你選擇的答案適合你! – JustCarty