我遇到了问题。在这里,我是一个关联数组名称 $ arr 。我通过输入传递了这一点。提交表单后,当我想访问它时,显示 Undefined index:paper (未定义的索引:纸张)。这是我的PHP代码。昨晚我也尝试解决此问题,但不能解决。提前致谢。
<?php
$arr = array('book' => '20' ,'pen' => '10' ,'paper' => '50' , );
if($_SERVER["REQUEST_METHOD"] == "POST") {
$new_arr = $_POST['arr2'];
echo $new_arr['paper'];
}
?>
<form action="" method="POST">
<br><br>
<input type="hidden" value="<?php echo $arr ?>" name="arr2"><br>
<input type="submit" name="" value="submit">
</form>
答案 0 :(得分:0)
首先将数组作为json
<input type="hidden" value="<?php echo json_encode($arr) ?>" name="arr2"><br>
您需要在$arr
中提供密钥,如下所示
<?php
$arr = array('book' => '20' ,'pen' => '10' ,'paper' => '50');
if($_SERVER["REQUEST_METHOD"] == "POST") {
$new_arr = json_decode($_POST['arr2'],true);
echo $new_arr['paper'];
}
?>
答案 1 :(得分:0)
echo $arr
只会产生“ Array”,因此对您没有帮助。但是您可以使用serialize
和unserialize
:
<?php
$arr = array('book' => '20' ,'pen' => '10' ,'paper' => '50' , );
if($_SERVER["REQUEST_METHOD"] == "POST") {
$new_arr = unserialize($_POST['arr2']);
echo $new_arr['paper'];
}
?>
<form action="" method="POST">
<br><br>
<input type="hidden" value="<?php echo serialize($arr) ?>" name="arr2"><br>
<input type="submit" name="" value="submit">
</form>
答案 2 :(得分:0)
尝试此代码
将input hidden
传递名称用作array key
的for循环
<?php
$arr = array('book' => '20' ,'pen' => '10' ,'paper' => '50' , );
if($_SERVER["REQUEST_METHOD"] == "POST") {
$new_arr = $_POST['paper'];
//print_r($new_arr);
echo $new_arr;
}
?>
<form action="" method="POST">
<br><br>
<?php foreach($arr as $k=>$v){
?>
<input type="text" value="<?php echo $v ?>" name="<?php echo $k?>"><br>
<?php
}
?>
<input type="submit" name="" value="submit">
</form>
答案 3 :(得分:0)
简单。首先对数组进行编码,以文本形式存储在单个元素内,然后对相同的值进行解码。
<?php
$arr = json_encode(array('book' => '20' , 'pen' => '10' , 'paper' => '50'));
if($_SERVER["REQUEST_METHOD"] == "POST") {
$new_arr = json_decode($_POST['arr2'], TRUE);
echo $new_arr['book'];
echo $new_arr['pen'];
echo $new_arr['paper'];
}
?>
<form action="" method="POST">
<input type="hidden" value='<?php echo $arr; ?>' name="arr2"><br>
<input type="submit" name="" value="submit">
</form>