0

我在删除购物车项目的会话数组中的项目时遇到问题。以下代码应获取所选项目并将其从会话中删除。然而,最终结果与之前的会话相同,没有任何内容被删除。我通过谷歌搜索看到了类似的问题,但还没有找到可行的解决方案。这是精简的代码:

<?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
?>

以下是 print_r 给出的以下内容(使用“7”作为已删除项目的示例):

$removeditem: 
7

$_SESSION['stuff'] (before and after removal)
Array
(
    [0] => 7
    [1] => 24
    [2] => 36
)

我错过了一些明显的东西吗?

4

4 回答 4

7

您正在删除 KEY 等于 $removedItem 的项目。在您的示例中,我认为您正在尝试删除 VALUE 等于 removeItem 的元素。在这种情况下,您需要执行一个 foreach 循环来识别键,然后将其删除。

foreach($_SESSION['stuff'] as $k => $v) {
  if($v == $removeditem)
    unset($_SESSION['stuff'][$k]);
}
于 2010-08-23T06:38:56.733 回答
3

您需要先获取key元素的,然后再获取unset它。这是您应该使用的代码:

if(($key = array_search($removeditem, $_SESSION['stuff'])) !== FALSE)
     unset($_SESSION['stuff'][$key]);
于 2010-08-23T06:43:15.423 回答
0

最简单的方法是:

<?php

    session_start();
    $removeditem = $_GET['item'];

    $temp = array_flip($_SESSION['stuff']);

    unset($_SESSION['stuff'][$temp[removeditem]]);

?>

PS 未测试...只是一个概念。

于 2010-08-23T06:53:54.043 回答
0

7 是数组中的值而不是键,因此使用键 7 取消设置将不起作用。您要做的是将数组中的每个项目与要删除的项目进行比较 ($_GET['item']) ,检索其密钥并取消设置。

于 2010-08-23T06:58:49.323 回答