我正在尝试向session['cart']['qty']
添加1,如果它不是新条目,并且如果它是新项目,则只会将该项目添加到session['cart']
。
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 :(得分: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);
}
}
你也可以使用类似的减量。
答案 1 :(得分: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'];
多维数组不能那样工作。
您正尝试从阵列qty
访问密钥$_SESSION['cart']['pid']
,但这不存在。这两个键是兄弟姐妹。