How to increment the session array value?

倖福魔咒の 提交于 2019-12-24 20:04:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!