简体   繁体   English

如何以隐藏在html表单中的输入类型传递php数组

[英]How to pass php array in input type hidden in html form

I want to pass my php array in my form input type as hidden.i have tried many times but it is giving me an array (key=>value,key=>value) in my input form. 我想将我的php数组传递给表单输入类型为hidden.i,我已经尝试了很多次,但是在我的输入表单中却给了我一个数组(键=>值,键=>值)。

This is my php code have a array. 这是我的PHP代码有一个数组。

 $my_arr = array();
 $my_arr['key']="value"; 

This is my html code 这是我的html代码

 <form method="post" action="next.php">
 <input type="hidden" name="my_form_data" value="<?php print_r($my_arr) ?>">
 <button name="submit_btn">Submit</button>
</form>

Any one please help me to pass php array in my input hidden element and how to get it in next page. 任何人都可以帮助我在我的输入隐藏元素中传递php数组,以及如何在下一页中获取它。

The easiest way is to make json as string by json_encode and then decode at the time of retrieve by json_decode , 最简单的方法是通过json_encode将json制成字符串,然后在通过json_decode进行检索时进行json_decode

<form method="post" action="next.php">
<input type="hidden" name="my_form_data" value="<?php echo json_encode($my_arr); ?>">
<button name="submit_btn">Submit</button>
</form> 
$hiddenvariable=array("apple","banana","cat");
foreach($hiddenvariable as $value)
{
  echo '<input type="hidden" name="my_form_data[]" value="'. $value. '">';
}

Making an array first then extracting an each elements using foreach and passing those values into hidden value. 首先创建一个数组,然后使用foreach提取每个元素并将这些值传递给隐藏值。

If I'm understanding you correctly, you can try this: 如果我对您的理解正确,则可以尝试以下操作:

<form method="post" action="next.php">
 <input type="hidden" name="my_form_data" value="<?php echo htmlspecialchars(serialize($my_arr)) ?>">
 <button name="submit_btn">Submit</button>
</form>

Then in next.php you unserialize to get the PHP data structure back: 然后在next.phpnext.php序列化以获取PHP数据结构:

<?php
$my_arr = unserialize($_POST["my_form_data"]);

Use my_form_data[] in name 在名称中使用my_form_data[]

<form method="post" action="next.php">
  <input type="hidden" name="my_form_data" value="<?php echo htmlentities(serialize($my_arr));?>">
</form>

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

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