假设我有这个特定的会话变量,$_SESSION['cart_'.$itemid].
是否可以对会话变量进行排序并找到带索引的一次'cart_'.$itemid并取消设置?
当然.你可以做点什么
foreach ($_SESSION as $key=>$val) {
// Look for "cart_" at the front of the array key
if (strpos($key, "cart_") === 0) {
unset($_SESSION[$key]);
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用相同的东西array_keys():
foreach (array_keys($_SESSION) as $key) {
// Look for "cart_" at the front of the array key
if (strpos($key, "cart_") === 0) {
unset($_SESSION[$key]);
}
}
Run Code Online (Sandbox Code Playgroud)
附录
如果我可以提出设计建议,如果你有能力改变这种结构,我会建议将这些购物车项目存储为数组.然后,数组将值包含在其中的项ID中.
// Updated after comments....
$_SESSION['cart'] = array();
// Add to cart like this:
$_SESSION['cart'][$itemId] = $new_quantity;
Run Code Online (Sandbox Code Playgroud)
这样可以更轻松地执行以下操作:
foreach ($_SESSION['cart'] as $item=>$quantity) {
// process the cart
}
Run Code Online (Sandbox Code Playgroud)