[英]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.