如何通过HTML表单发送PHP数组(使用输入标记)
I would like to send an array in the input form element.
My array:
Array( [0] => 55 [1] => 1 [2] => 4 )
HTML <input>
tag:
<input type="hidden" name="category" value="'.$category.'" />
This is the URL my code resulted in:
http://localhost/search?&category%5B%5D=55&category%5B%5D=1&category%5B%5D=4
But I also get this PHP Notice:
PHP Notice: Array to string conversion
How do I send an array via HTML form correctly?
============================
I found this solution:
foreach ($category as $item) {
echo '<input type="hidden" name="categories[]" value="'.$item.'" />';
}
Prepare your array $category
. Example:
echo '<div align="center">
<form method="GET" action="/search" />
<input type="hidden" name="search" value="'.$search.'" />';
foreach ($category as $item){
echo '<input type="hidden" name="categories[]" value="'.$item.'" />';
}
echo '<input type="submit">
</form>
</div>';
And get:
if(isset($_GET['categories'])) {
$categories = $_GET['categories'];
}
我想在输入表单元素中发送一个数组。 p>
我的数组: p>
数组([0] =&gt; 55 [1] =&gt; 1 [2] =&gt; 4)
code> pre >
HTML &lt; input&gt; code>标记: p>
&lt; input type =“hidden”name =“category”value =“'。$ category。'”/&gt;
code> pre>
这是我的代码产生的网址: p>
HTTP://本地主机/搜索&安培;类别%5B%5D = 55&安培;类别%5B%5D = 1&安培;类别%5B%5D = 4
代码> PRE>
但我也得到了这个PHP注意事项: p>
PHP注意:数组转换为字符串 p>
blockquote>
如何正确地通过HTML表单发送数组? p>
============================ p>
我找到了这个解决方案: strong> p>
foreach($ category as $ item){
echo' &lt; input type =“hidden”name =“categories []”value =“'。$ item。'”/&gt;';
}
code> pre>
准备阵列 $ category code>。 示例: p>
echo'&lt; div align =“center”&gt;
&lt; form method =“GET”action =“/ search”/&gt;
&lt; input type =“hidden”name =“search”value =“'。$ search。'”/&gt;';
foreach($ category as $ item){
echo'&lt; input type =“hidden”name =“categories []”value =“'。$ item。'”/&gt;';
}
echo'&lt; input type =“submit”&gt;
&lt; / form&gt;
&lt; / div&gt;';
code> pre>
获取: p>
if(isset($ _ GET ['categories'])){
$ categories = $ _GET ['categories'];
}
code> pre>
div>
The easiest way to do that is to convert your categories array to JSON and back.
echo '<input type="hidden" name="category" value="' . json_encode($category) . '" />';
... and when you send your form, parse the JSON back to the array:
$category = json_decode($_GET["category"]);