Php 如何检查数组中是否存在值,以及该值是否增加
我有以下代码。我希望Php 如何检查数组中是否存在值,以及该值是否增加,php,Php,我有以下代码。我希望elseif部分检查$pId是否已在数组中,如果已在数组中,我希望增加其数量和价格,而不是向数组中添加新的$pId 我不知道我是否使用了错误的方法,或者我的数组结构是否错误,但我无法让它增加这些值 if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); $_SESSION['cart']['pid'][] = $pid; $_SESSION['cart']['pid']['price'
elseif
部分检查$pId
是否已在数组中,如果已在数组中,我希望增加其数量和价格,而不是向数组中添加新的$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;
}
我在数组中添加了一个额外的维度,因此您可以轻松地选择它
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
代表什么,但乍一看,它并没有真正的描述性。也许产品
会是一个更好的键?@repwhoringpeehaha当前值加上新值。例如price+=
;