如何从PHP会话数组中删除一个变量 [英] How to remove a variable from a PHP session array
本文介绍了如何从PHP会话数组中删除一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的PHP code用于变量添加到会话:
< PHP
在session_start();
如果(使用isset($ _ GET ['名']))
{
$名称=使用isset($ _ SESSION ['名'])? $ _SESSION ['名']:阵列();
$名称[] = $ _GET ['名'];
$ _SESSION ['名'] = $名称;
}
如果(使用isset($ _ POST ['删除']))
{
未设置($ _ SESSION ['名']);
}
?>
< pre> < PHP的print_r($ _ SESSION); ?> < / pre><表格名称=输入行动=的index.php名=<?PHP的echo $列表>方法=后>
<输入类型=提交名称=添加VALUE =添加/>
< /表及GT;<表格名称=输入行动=?index.php文件名=< PHP的echo $列表2>?方法=后>
<输入类型=提交名称=删除价值=删除/>
< /表及GT;
我想删除当用户选择删除即在 $列表2
显示从会话数组变量。
但是,当我取消设置,阵列中的所有变量都将被删除。
我如何删除只有一个变量?
解决方案
如果(使用isset($ _ POST ['删除'])){
$键= array_search($ _ GET ['名'],$ _ SESSION ['名']);
如果($关键!== FALSE)
未设置($ _ SESSION ['名'] [$关键]);
$ _SESSION [名称] = array_values($ _ SESSION [名称]);
}
由于 $ _ SESSION ['名']
是一个数组,你需要找到一个指向名称值你感兴趣的数组键,最后一行重新安排阵列,以便下次使用的索引。
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屋!
查看全文