gpt4 book ai didi

php - 从 foreach 循环中删除 session 数组变量

转载 作者:行者123 更新时间:2023-11-29 14:10:17 24 4
gpt4 key购买 nike

我正在尝试编写一个可以从 session 数组中删除变量的代码

这是我的代码

index.php

    <?php
if(isset($_POST['add']))
{
$_SESSION['temp'][]=$_POST['rfield'];
$_SESSION['scol_id'][]=$_POST['scol_id'];

}
if(isset($_SESSION['temp']))
{
?>
<table width="100%" border="0" class = "table">
<?php
$x=0;
foreach($_SESSION['temp'] as $temp)
{
?>
<tr><td>
<?php echo $temp; ?>
</td>
<td><a href="removerf.php?id=<?php echo $x; ?>" rel="tooltip" title="remove" class="link"><i class="icon-remove"></i></a></td>
</tr>
<?php
$x++;
}
?>
</table>
<?php
}
?>

removalf.php

    <?php
session_start();

unset($_SESSION['temp'][$_GET['id']]);

header("location:reportmaker.php");

?>

我的代码的问题是有时它可以删除变量,有时则不能

由于某种奇怪的原因,它也无法删除数组的第一个变量

我错过了什么吗?

提前致谢

最佳答案

我不会依赖 $x 是正确的数组键。你能试试这个吗?

<?php
if(isset($_POST['add']))
{
$_SESSION['temp'][]=$_POST['rfield'];
$_SESSION['scol_id'][]=$_POST['scol_id'];
}
if(isset($_SESSION['temp']))
{
?>
<table width="100%" border="0" class = "table">
<?php
foreach($_SESSION['temp'] as $key => $temp)
{
?>
<tr><td>
<?php echo $temp; ?>
</td>
<td><a href="removerf.php?id=<?php echo $key; ?>" rel="tooltip" title="remove" class="link"><i class="icon-remove"></i></a></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>

每当您从临时数组中删除键时,依赖 $x 作为数组键都会导致问题。如果您的临时数组是:

array(
0 => 'foo',
1 => 'bar'
)

并且您从数组中删除 0,即使数组键 0 不存在,$x 仍将从 0 开始。即,您正在对数组中当前存在的数组键做出假设。

关于 foreach:

foreach($myArray as $arrayKey => $arrayValue){
//$arrayKey is the array key of the element / index
//$arrayValue is the actual element that is stored.
}

关于php - 从 foreach 循环中删除 session 数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13604585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com