【问题标题】:Get data from multiple inputs with the same name从多个同名输入中获取数据
【发布时间】:2018-09-05 02:15:13
【问题描述】:

我有一个大表格,我通过 ajax 将这些数据传递给 php。我使用 jQuery serialize 函数将这些数据保存在字符串中。 这是我的代码

var form_data = jQuery(this).serializeArray();
form_data = JSON.stringify(form_data);

在 php 中,我通过 json_decode 函数将其转换为数组。

这里是这个数组的一个例子

Array
(
[0] => Array
(
    [name] => fname
    [value] => MyFirstName
)

[1] => Array
(
    [name] => lname
    [value] => MyLastName
)
 [2] => Array
(
    [name] => institution_name[]
    [value] => institution1
)

[3] => Array
(
    [name] => degree_name[]
    [value] => Graduated
)
[4] => Array
(
    [name] => institution_name[]
    [value] => institution2
)
[5] => Array
(
    [name] => degree_name[]
    [value] => Graduating
)
)

我能够在循环中获取其他输入字段,但难以从具有相同名称的输入字段中获取值。例如,在上面的示例中,我们有多个 degree_name 和 authority_name。 我会感谢您的建议,因为我是 php 新手。

【问题讨论】:

    标签: php jquery html


    【解决方案1】:

    我以前用过foreach

       $new = array();
        foreach ($_POST as $key => $value) {
            $new[$key] => $value;
        }
    
        var_dump($new);
    

    【讨论】:

      【解决方案2】:

      PHP 处理多个同名表单输入的方法是将它们转换为数组。

      这就是他们名字中的[] 后缀的含义。

      因此,要访问它们的各种值(即对于该名称的每个字段),请查看数组内部。

      $_POST['degree_name'][0]; //the value of the first field with [name=degree_name]
      $_POST['degree_name'][1]; //the value of the 2nd field with [name=degree_name]
      //...etc
      

      【讨论】:

      • 我已经尝试过了,但它没有返回正确的值。例如,在第一个 degree[] 字段值是 Graduation 然后对于 [0] 它返回 'G' 对于 [1] 它返回 'r' 等等。
      猜你喜欢
      • 2020-12-04
      • 2018-09-13
      • 2014-02-10
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2022-08-14
      • 1970-01-01
      相关资源
      最近更新 更多