简体   繁体   中英

Unsetting session variables from a foreach loop PHP

The products in my cart are stored by ajax and set into sessions. look my code from cart_functions.php (here are functions for my buttons in cart).

if (isset($_GET['action'])) {
  $action = $_GET['action'];   //get button action name
  $prod   = $_GET['prod_id'];  // id of the product
  $prodname = 'product_'.$prod;// name of the product



 switch ($action) {
   case 'add':
       $result = add_prod($prod, $prodname);
   break;
  ///rest of switch....(not important for now)

This is the function that adds a product into session

function add_prod($prod, $prodname){
  //add function
$_SESSION[$prodname] = 1;
return ['result'=>'success'];
}

the name of this session is like this--> $_SESSION['product_123'] etc.

Ok so now i want to unset all the $_SESSION[$prodname] . In other pages $_SESSION[$prodname] is $_SESSION['product_123'] . So as in my cart i have multiple $_SESSION[$prodname] i want to unset when the client submit order. How i can get all $_SESSION['product_123'],$_SESSION['product_1234']...and so on ?

I dont know if this helps but to count my products i used a code from a help i had here... look

$product_count = count(array_filter(array_keys($_SESSION), function($x) {
            return substr($x, 0, 8) == 'product_';
            }));

At the point at which you are hoping to unset the particular session element, have you tried

unset($_SESSION[$product]);

as that should be all that is required. I searched your code but could not find where you were attemting to unset anything.

尝试session_destroy()创建一个类似reset.php之类的新文件,然后将session_destroy()放到肯定会擦除所有会话的位置。

You'd better use an array

$_SESSION['products'][$id]

It allow you to easily loop through your products and you can reset it simply by

unset($_SESSION['products'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM