我有一个包含动物的阵列。我使用foreach循环打印出数组。我想更新特定键的值,而不更改具有不同键的任何其他值。我在每个键旁边都有一个更新输入框,用于输入值。例如,当我键入键0的值时,所有其他键值也会改变,而不仅仅是0
所以我的输出是这样的:
The value of $_SESSION['0'] is 'cat' // i want to change cat to something else
The value of $_SESSION['1'] is 'dog' // dog to something else
The value of $_SESSION['2'] is 'mouse' /mouse to something else
这是我的代码而且令人沮丧,因为我在foreach循环中为每个输入添加了$ key ...
**code
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
// put the array in a session variable
$_SESSION['animals']=$my_array;
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
// getting the updated value from input box
if (isset($_POST["submit"])) {
$aaa = $_POST['aaa'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key] = $aaa;
}
?>
<form method="post" action="testthis.php">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<input type="submit" value="Add to cart" name="submit"/></div>
</form>
<?php
}
echo"<br/>---------------------------------------------------------<br/>";
//echoing out the results again for the updated version
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
答案 0 :(得分:0)
请尝试以下代码。
编辑:
1)将isset($_POST["submit"])
移到foreach
循环之外,这样它就不会更新所有会话。
2)使用要更新的key值的隐藏输入,以便我们只关注一个要更新的键。
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
$aaa = $_POST['aaa'];
$key_var = $_POST['ke'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
// getting the updated value from input box
?>
<form method="post" action="">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke" value="<?php echo $key; ?>">
<input type="submit" value="Add to cart" name="submit"/></div>
</form>
<?php
}
echo"<br/>---------------------------------------------------------<br/>";
//echoing out the results again for the updated version
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>