问题
I am using this on a shopping cart
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[] = $_getvars['id'];
$session->set('cart', $data);
}
$_getvars['id']
is productid, and on each click, a new array element will be added to the session. It works fine as it is now, but if a product is chosen more than once a new array will be added, how can change it that productid will be array offset and the value will be incremented from 1 each time to reflect the quantity?
$i = 1;
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[$_getvars['id']] = $i++;
$session->set('cart', $data);
}
but this code each time resets to 1. How to fix it? Or any better array structure for a shopping cart?
回答1:
If it's not set, set it to zero, then always add one.
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
$data[$_getvars['id']] += 1;
$session->set('cart', $data);
}
Or you could add a dynamic quantity
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
// $_GET['qty'] OR 1, if not set
$qty = (!empty($_getvars['qty']))? $_getvars['qty']: 1;
$data[$_getvars['id']] += $qty;
$session->set('cart', $data);
}
来源:https://stackoverflow.com/questions/58527391/how-to-increment-the-session-array-value