简体   繁体   English

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

[英]removing session array variables from a foreach loop

im trying to wrote a code where i can remove variables from a session array 我试图写一个代码,我可以从会话数组中删除变量

here is my code 这是我的代码

index.php 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 removerf.php

    <?php
    session_start();

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

    header("location:reportmaker.php");

    ?>

the problem with my code is that sometimes it can delete variables and sometimes it dont 我的代码的问题是,有时它可以删除变量,有时却不删除

it also cant delete the first variable of the array for some strange reason 由于某些奇怪的原因,它也无法删除数组的第一个变量

am i missing something? 我想念什么吗?

thanks in advance 提前致谢

I wouldn't rely on $x being the correct array key. 我不会依靠$ x作为正确的数组键。 Could you try this instead? 您能试试看吗?

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

Relying on $x to be the array key will lead to issues whenever you delete a key from the temp array. 每当您从临时数组中删除键时,依靠$ x作为数组键都会导致问题。 If your temp array is: 如果您的临时数组为:

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

and you delete 0 from the array, $x will still start off as 0, even though the array key 0 doesn't exist. 并且您从阵列中删除0,即使阵列键0不存在,$ x仍将从0开始。 ie you're making assumptions about the array keys that currently exist in your array. 即,您要对当前数组中存在的数组键进行假设。

In regards to foreach: 关于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