2012-04-25 42 views
0

我有以下代碼。我想elseif部分檢查$pId是否已經在陣列中,如果是我想增加其quantityprice,而不是將新的$pId添加到陣列。如何檢查數組中是否存在某個值,以及它是否增加該值

我不知道我是否使用了錯誤的方法,或者如果我的陣列結構是錯誤的,但我不能得到它來增加這些值

if (!isset($_SESSION['cart'])) { 
    $_SESSION['cart'] = array(); 
    $_SESSION['cart']['pid'][] = $pid; 
    $_SESSION['cart']['pid']['price'] = $price; 
    $_SESSION['cart']['pid']['quantity'] = $quantity; 
    $_SESSION['cart']['total_price'] = $price; 
    $_SESSION['cart']['total_items'] = $quantity; 
}elseif(array_key_exists($pid, $_SESSION['cart'])){ 
    //increase price 
    //increase quantity 
}else{ 
    $_SESSION['cart']['pid'][] = $pid; 
    $_SESSION['cart']['pid']['price'] = $price; 
    $_SESSION['cart']['total_price'] += $price; 
    $_SESSION['cart']['total_items'] += $quantity; 
} 
+0

增加什麼? – PeeHaa 2012-04-25 22:48:03

+0

@RepWhoringPeeHaa當前值加上新值。例如'價格+ ='; – code511788465541441 2012-04-25 22:49:38

回答

1

我已經添加了一個額外的維度數組等等你可以很容易地選擇它。

if (!isset($_SESSION['cart'])) { 
    $_SESSION['cart'] = array('pid' => array(), 'total_price' => 0, 'total_items' => 0); 
    $_SESSION['cart']['pid'][$pid] = array(); 
    $_SESSION['cart']['pid'][$pid]['price'] = $price; 
    $_SESSION['cart']['pid'][$pid]['quantity'] = $quantity; 
    $_SESSION['cart']['total_price'] = $price; 
    $_SESSION['cart']['total_items'] = $quantity; 
}elseif(array_key_exists($pid, $_SESSION['cart']['pid'])){ 
    $_SESSION['cart']['pid'][$pid]['price'] = 'new price'; 
    $_SESSION['cart']['pid'][$pid]['quantity'] = 'new quantity'; 
}else{ 
    $_SESSION['cart']['pid'][$pid]['price'] = $price; 
    $_SESSION['cart']['total_price'] += $price; 
    $_SESSION['cart']['total_items'] += $quantity; 
} 

我不知道pid代表什麼,但第一眼看上去真的描述。也許products會是一個更好的鑰匙?

+0

非常感謝! – code511788465541441 2012-04-25 23:05:43