如何从 PHP 会话数组中删除变量 [英] How to remove a variable from a PHP session array
问题描述
我有用于向会话添加变量的 PHP 代码:
<预><?php print_r($_SESSION);?>
<form name="input" action="index.php?name=<?php echo $list ?>"方法=发布"><input type="submit" name="add"value="Add"/></表单><form name="input" action="index.php?name=<?php echo $list2 ?>"方法=发布"><input type="submit" name="remove" value="Remove"/></表单>
当用户选择删除"时,我想从会话数组中删除 $list2
中显示的变量.
但是当我取消设置时,数组中的所有变量都会被删除.
如何只删除一个变量?
if (isset($_POST['remove'])) {$key=array_search($_GET['name'],$_SESSION['name']);如果($key!==false)未设置($_SESSION['name'][$key]);$_SESSION["name"] = array_values($_SESSION["name"]);}
由于$_SESSION['name']
是一个数组,所以需要找到指向你感兴趣的name值的数组key.最后一行重新排列数组的索引供下次使用.
I have PHP code that is used to add variables to a session:
<?php
session_start();
if(isset($_GET['name']))
{
$name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
$name[] = $_GET['name'];
$_SESSION['name'] = $name;
}
if (isset($_POST['remove']))
{
unset($_SESSION['name']);
}
?>
<pre> <?php print_r($_SESSION); ?> </pre>
<form name="input" action="index.php?name=<?php echo $list ?>" method="post">
<input type="submit" name ="add"value="Add" />
</form>
<form name="input" action="index.php?name=<?php echo $list2 ?>" method="post">
<input type="submit" name="remove" value="Remove" />
</form>
I want to remove the variable that is shown in $list2
from the session array when the user chooses 'Remove'.
But when I unset, ALL the variables in the array are deleted.
How I can delete just one variable?
if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name']
is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.
这篇关于如何从 PHP 会话数组中删除变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!