如何增加会话数组值? [英] How to increment the session array value?

查看:51
本文介绍了如何增加会话数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在购物车上使用这个

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    $data[] = $_getvars['id'];
    $session->set('cart', $data);
} 

$_getvars['id'] 是 productid,每次点击时,都会将一个新的数组元素添加到会话中.它现在工作正常,但是如果一个产品被多次选择,一个新的数组将被添加,如何改变它,productid 将是数组偏移量,并且值每次从 1 递增以反映数量?

$_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);
} 

但是这段代码每次都重置为1.如何解决?或者任何更好的购物车数组结构?

but this code each time resets to 1. How to fix it? Or any better array structure for a shopping cart?

推荐答案

如果没有设置,设置为零,然后总是加一.

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);
} 

这篇关于如何增加会话数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆