【问题标题】:How PHP handles 2 dimensional array HTML form input while using Laravel使用 Laravel 时 PHP 如何处理二维数组 HTML 表单输入
【发布时间】:2015-06-23 18:29:26
【问题描述】:

我正在使用 Laravel 5 开发一个以二维数组作为输入的 HTML 表单。目的是存储一些联系人,每个联系人的输入字段可以由 JQuery 动态添加或删除。

我想使用空括号 [] 这样就不需要维护索引。所以我尝试了 2 例 HTML 表单输入代码。以下是简化示例:

案例 1:

Person 1:
<input type="text" name="contacts[][surname]">
<input type="text" name="contacts[][first_name]">
<input type="checkbox" name="contacts[][VIP]">

Person 2:
<input type="text" name="contacts[][surname]">
<input type="text" name="contacts[][first_name]">
<input type="checkbox" name="contacts[][VIP]">

但我使用 die dump 检查的数组,即 dd($request-&gt;input('contacts')); 返回:

array:4 [
  0 => array:1 ["surname" => "Some Value" ]
  1 => array:1 ["first_name" => "Some Value" ]
  2 => array:1 ["surname" => "Some Value" ]
  3 => array:1 ["first_name" => "Some Value" ]
]

让我们暂时忘记复选框输入,因为它在未选中时根本不会返回任何内容。话虽如此,我已将其包含在此处,以防它是问题的根源。

案例 2

Person 1:
<input type="text" name="contacts[surname][]">
<input type="text" name="contacts[first_name][]">
<input type="checkbox" name="contacts[VIP][]">

Person 2:
<input type="text" name="contacts[surname][]">
<input type="text" name="contacts[first_name][]">
<input type="checkbox" name="contacts[VIP][]">

模具转储,即dd($request-&gt;input('contacts')); 返回以下:

array:2 [
  "surname" => array:2 [
    0 => "Some Value"
    1 => "Some Value"
  ]
  "first_name" => array:2 [
    0 => "Some Value"
    1 => "Some Value"
  ]
]

我想要什么

这给我们带来了问题。这是我想要的结果:

array:2 [
  0 => array:2 [
    "surname" => "Some Value"
    "first_name" => "Some Value"
  ]
  1 => array:2 [
    "surname" => "Some Value"
    "first_name" => "Some Value"
  ]
]

有没有办法做到这一点,如果有,我该如何实现?这是否意味着我必须维护一个索引?

【问题讨论】:

    标签: php jquery arrays laravel dimensional


    【解决方案1】:

    试试这个。

    Person 1:
    <input type="text" name="contacts[0][surname]">
    <input type="text" name="contacts[0][first_name]">
    <input type="checkbox" name="contacts[0][VIP]">
    
    Person 2:
    <input type="text" name="contacts[1][surname]">
    <input type="text" name="contacts[1][first_name]">
    <input type="checkbox" name="contacts[1][VIP]">
    

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 2016-08-04
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      相关资源
      最近更新 更多