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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应