[英]Removing a certain number out of a session array in PHP
I have a button next to all my 'shop items' that can remove one of the shop item, however i need it to just remove one, and not rid the entire array of the number, i thought this was possible by using a break statement when i found the number i want to remove, but it removes all of the numbers. 我所有的“商店商品”旁边都有一个按钮,可以删除其中一个商店商品,但是我需要它仅删除一个商店商品,而不是删除整个数字数组,我认为这可以通过使用break语句来实现当我找到要删除的号码时,它会删除所有号码。
if (isset($_GET['remove']) && isset($_SESSION['shopitems'])) {
if (in_array($_GET['remove'], $_SESSION['shopitems'])) {
for ($i = 0; $i < sizeof($_SESSION['shopitems']); $i++) {
if ($_SESSION['shopitems'][$i] == $_GET['remove']) {
$shopArray = $_SESSION['shopitems'];
if(sizeof($shopArray) == 1) {
$_SESSION['shopitems'] = null;
$_SESSION['added'] = null;
} else {
array_splice($shopArray, $i, $i);
$_SESSION['shopitems'] = $shopArray;
}
break;
}
}
}
}
Here i check if the URL contains the remove variable and the session is set, once i have done this, i check if the array contains the number that is put in the URL, if so i'll start a for loop and check if the key index of the session shop items is equal to the URL variable, if so i want to remove it, however if i use array_splice, suddenly they are all gone, is this because of the function i am using? 在这里,我检查URL是否包含remove变量并设置了会话,一旦完成此操作,我将检查数组是否包含URL中放入的数字,如果是,我将启动for循环并检查是否会话商店项目的关键索引等于URL变量,如果要删除它,那么,如果我使用array_splice,突然它们都消失了,这是因为我正在使用的功能吗? Or is the break not executing correctly? 还是中断执行不正确?
Why don't you try array_search() and unset() ? 为什么不尝试使用array_search()和unset()呢? It's easier, have a look at the code below and adapt it to your situation: 更简单,请看下面的代码,使其适应您的情况:
$array = [1, 5, 6, 12];
$wantToRemove = 5;
$key = array_search($wantToRemove, $array);
unset($array[$key]);
var_dump($array);
You can format your $_SESSION['shopitems']
like this : 您可以这样设置$_SESSION['shopitems']
格式:
$_SESSION['shopitems'] = array (
"item_id" => "item_info",
"item2_id" => "item2_info",
...
)
and do unset($_SESSION['shopitems'][$_GET['remove']])
. 并unset($_SESSION['shopitems'][$_GET['remove']])
。
Your code could be : 您的代码可能是:
if (isset($_GET['remove']) && isset($_SESSION['shopitems']))
if (isset($_SESSION['shopitems'][$_GET['remove']]))
unset($_SESSION['shopitems'][$_GET['remove']])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.