0 php variables session cart unset
我在购物车项目中删除会话数组中的项目时遇到问题.以下代码应采用所选项目并将其从会话中删除.然而,最终结果与之前的会话相同,没有删除任何内容.我通过谷歌搜索看到了类似的问题,但还没有找到可行的解决方案.这是精简代码:
<?php
session_start();
$removeditem = $_GET['item']; // this identifies the item to be removed
unset($_SESSION['stuff'][$removeditem]); // "stuff" is the existing array in the session
?>
Run Code Online (Sandbox Code Playgroud)
以下是print_r为以下内容提供的内容(使用"7"作为已删除项目的示例):
$removeditem:
7
$_SESSION['stuff'] (before and after removal)
Array
(
[0] => 7
[1] => 24
[2] => 36
)
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西吗
您正在删除KEY等于$ removedItem的项目.从您的示例中我可以看出,您正在尝试删除VALUE等于removedItem的元素.在这种情况下,您需要执行foreach循环以识别密钥,然后将其删除.
foreach($_SESSION['stuff'] as $k => $v) {
if($v == $removeditem)
unset($_SESSION['stuff'][$k]);
}
Run Code Online (Sandbox Code Playgroud)