dongtiao5094 2014-04-24 13:58
浏览 34
已采纳

如何取消设置$ _SESSION数组中的项目

i have 2 functions. First one is adding item to cart, second should delete specific item based on product id.

function AddToCart($pid) {
    if (isset($_SESSION['products']['prod_count'])) {
        $_SESSION['products']['prod_count'] ++;
        $incart = $_SESSION['products']['prod_count'];
        $_SESSION['products'][$incart]['product_id'] = $pid;
    } else {
        $_SESSION['products']['prod_count'] = 0;
        $incart = $_SESSION['products']['prod_count'];
        $_SESSION['products'][$incart]['product_id'] = $pid;
    }
}

function DeleteProduct($pid) {
    foreach ($_SESSION['products'] as $key => $my_value) {
        foreach ($my_value as $key => $product_id) {
            if ($product_id == $pid) {
                // do not know how to unset this product
            }
        }
    }
}

I need some idea on how to unset the product if $product_id == $pid or may be some other ideas how to achieve that.

My array look something like:

array(1) { ["products"]=> &array(4) 
                { ["prod_count"]=> int(2) 
                           [0]=> array(1) { ["product_id"]=> int(4)}
                           [1]=> array(1) { ["product_id"]=> int(10) } 
                           [2]=> array(1) { ["product_id"]=> int(11) } } }
  • 写回答

1条回答 默认 最新

  • doula4096 2014-04-24 14:06
    关注

    The following code would simply solve your problem:

        function DeleteProduct($pid) {
            foreach ($_SESSION['products'] as $key => $product) {
                if ($pid === $product['product_id']) {
                    unset($_SESSION['products'][$key]);
                }
            }
        }
    

    But to make your work alot easier in the future you could also build your array like this:

    $_SESSION['products'] = array(
        'product_id' => 'amount',
    );
    

    To add a product you would simply do:

    $_SESSION['products'][$product_id] += $amount;
    

    To count your products you could use:

    count($_SESSION['products']);
    

    Here is a simple example of what your functions could be like:

    function addProduct($pid, $value = 1) {
        $_SESSION['products'][$pid] += $value;
    }
    
    function removeProduct($pid) {
        unset($_SESSION['products'][$pid]);
    }
    
    function countProducts() {
        return count($_SESSION['products']);
    }
    

    Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?