繁体   English   中英

从foreach循环中删除会话数组变量

[英]removing session array variables from a foreach loop

我试图写一个代码,我可以从会话数组中删除变量

这是我的代码

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
        }
        ?>                          

removerf.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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM