从php中的会话关联数组中删除项目

时间:2022-05-29 12:14:58

I am really stuck with this. It is an array within an array such as:

我真的很困惑。它是一个数组中的数组,例如:

Array ( [0] => Array ( [item] => product1 [unitprice] => 15 [quantity] => 1 ) [1] => Array ( [item] => product2 [unitprice] => 15 [quantity] => 1 ) )

I have tried to remove a specific item using:

我试图使用以下方法删除特定项目:

$pid=$_GET['id']; (where id = product1)

$delete=array_splice($_SESSION['cart'], array_search($id, $_SESSION['cart']), 1);
unset($delete);    

print_r($_SESSION['cart']);

This seems to randomly remove items. Any help would be greatly appreciated

这似乎随​​机删除项目。任何帮助将不胜感激

2 个解决方案

#1


2  

<?php 
function searchForItem($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['item'] === $id) {
           return $key;
       }
   }
   return null;
}

$pid=$_GET['id'];

$id = searchForItem($pid, $_SESSION['cart']);

unset($_SESSION['cart'][$id]);

?>

#2


0  

you mean:

foreach($_SESSION['cart'] as $index => $v) { 
    if(($key = array_search($pid, $v)) !== false) {
        unset($_SESSION['cart'][$index]);
    }
}

#1


2  

<?php 
function searchForItem($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['item'] === $id) {
           return $key;
       }
   }
   return null;
}

$pid=$_GET['id'];

$id = searchForItem($pid, $_SESSION['cart']);

unset($_SESSION['cart'][$id]);

?>

#2


0  

you mean:

foreach($_SESSION['cart'] as $index => $v) { 
    if(($key = array_search($pid, $v)) !== false) {
        unset($_SESSION['cart'][$index]);
    }
}