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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大