简体   繁体   English

HTML 表单输入创建 arrays 数组

[英]HTML form inputs create array of arrays

I haveinputs that are defined like this in html:我在 html 中有这样定义的输入:

 <input type="text" name="options[name][]" value ="Name" />
 <input type="text" name="options[selling_price][]" value = "10" />

 <input type="text" name="options[name][]" value ="Name 2" />
 <input type="text" name="options[selling_price][]" value = "20" />

... ...

When I process this on the server I get:当我在服务器上处理这个时,我得到:

"options" => array:2 [▼
    "name" => array:2 [▼
      0 => "Name"
      1 => "Name 2"
    ]
    "selling_price" => array:2 [▼
      0 => "10"
      1 => "20"
    ]

What I would like to get is:我想得到的是:

array:2 [▼
  0 => array:2 [▼
    "name" => "Name"
    "selling_price" => 10
  ]
  1 => array:2 [▼
    "name" => "Name 2"
    "selling_price" => 20
  ]
]

Is this possible in html and make it dynamic so I can keep adding them in javascript?这在 html 中是否可能并使其动态化,以便我可以继续在 javascript 中添加它们?

The only way I have found to do it is to make a counter variable and do options[counter][name]我发现这样做的唯一方法是创建一个计数器变量并执行options[counter][name]

The way you came up with, adding the counter in the name, is correct.您想出的方式,在名称中添加计数器,是正确的。 There is no built-in way to keep automatically increasing the counter while grouping specific form fields.在对特定表单字段进行分组时,没有内置方法可以自动增加计数器。 So you'll have to keep track of the current count and increment this as well as putting it into the name attribute when adding a new set of fields.因此,您必须跟踪当前计数并增加它,并在添加一组新字段时将其放入 name 属性中。

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

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