我有以下代码。我希望elseif
部分检查数组中是否已有$pId
,如果是,我想增加quantity
和price
而不是添加新$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 :(得分: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
会是更好的关键吗?