将表单提交到JSON文件时保留数组

将表单提交到JSON文件时保留数组

问题描述:

I have a form that takes in data and writes to a JSON form in PHP.

I needed to submit an array as a numeric input but it keeps giving me a string. Is it possible to enable the form to submit as an array via text input box?

Form example:

<input type="text" name="arraytobepushed[]" placeholder="EG: 1000,2000,3000" />

The output is:

{
"obj": [{
   "arraytobepushed": ["1000,2000,3000"]
       }]
}

我有一个表单,它接收数据并在PHP中写入JSON表单。 p> \ n

我需要提交一个数组作为数字输入,但它不断给我一个字符串。 是否可以通过文本输入框将表单作为数组提交? p>

表单示例: p>

 &lt; input type =  “text”name =“arraytobepushed []”placeholder =“EG:1000,2000,3000”/&gt; 
  code>  pre> 
 
 

输出为: p> \ n

  {
“obj”:[{
“arraytobepushed”:[“1000,2000,3000”] 
}] 
} 
  code>  pre>  
  div>

You could turn the text into an array by using explode() So you would have something like this:

<?PHP
  $myArray = explode(',', $_POST['arraytobepushed[]']);
?>

The explode() function splits everything separated by the first argument (in this case a comma) you pass and puts it into an array.

So if your inputted was 1000, 2000, 3000 your $myArray would look like:

index 0 = "1000" ($myArray[0])

index 1 = "2000" ($myArray[1])

index 2 = "3000" ($myArray[2])

Keep in mind that the values are still strings, not integers. If you want to make them integers you can do this:

$myArray = array_map('intval', explode(',', $_POST['arraytobepushed[]'])); 

This makes all your elements into integers like so:

index 0 = 1000 ($myArray[0])

index 1 = 2000 ($myArray[1])

index 2 = 3000 ($myArray[2])

No. Forms submit text.

PHP special cases fields with [] in the name as fields to be expressed in an array. It has no special case feature to treat a field as a number instead of a string. You need to convert the data explicitly.