表单中使用数组格式的输入字段名称

表单中使用数组格式的输入字段名称

本文介绍了如何在发布到 PHP 的 HTML 表单中使用数组格式的输入字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解使用数组格式的 HTML 输入名称的基础知识.如果我有一个包含可变数量的项目"输入的表单,我可能会为每个输入做这样的事情:

I understand the basics of using the array-formatted HTML input names. If I had a form with a variable number of 'item' inputs I might do something like this for each of them:

<input name='item[]' type='text' />

当我从 $_POST 数组中检索项目时,我可以像这样迭代它们:

And when I retrieve the items from the $_POST array I could iterate over them like so:

$items = $_POST['item'];
foreach($items as $item) {
}

但我的问题稍微复杂一些.我有一个表单,用户可以在其中单击添加一个"按钮,然后在表单底部的数字处会出现一个新行.每个新行都包含一个名称"和描述"输入.

But my question is slightly more complicated. I have a form where users can click a button "add one" and a new row will appear at the bottom number of the form. Each new row contains a 'name' and 'description' input.

所以最初我想我会这样做:

So initially I thought I would do this:

<input name='item[name][]' type='text' />
<input name='item[description][]' type='text' />

然后像这样迭代它们:

$items = $_POST['item'];
foreach($items as $item) {
  print $item['name'] . ' ' . $item['description'];
}

但是它没有像我希望的那样工作,而是构造了item"数组,这样我就可以以 $item['name'][0] 而不是 $item['name'][0] 访问第一个项目名称代码>$item[0]['name'].

But instead of working as I hoped, it instead structures the 'item' array such that I would access the first item name as $item['name'][0] rather than as $item[0]['name'].

然后我翻转它,以便我的输入被命名为:

So then I flipped it so that my inputs were named as such:

<input name='item[][name]' type='text' />
<input name='item[][description]' type='text' />

但这导致每个名称"和每个描述"都有一个单独的项目",而不是将每一对组合成一个项目".

But this resulted in a separate 'item' for each 'name' and for each 'description' rather than grouping each pair in a single 'item'.

我真的不喜欢有名称"数组和单独的描述"数组.我更喜欢 'item' 数组,每个数组包含一个 'name' 和一个 'description' 字段.有没有办法在不生成我的 javascript 中的索引的情况下完成此操作?由于人们可以动态添加和删除这些,因此我的 javascript 很难计算下一项的适当索引.一般没有办法做到这一点吗?

I really dislike having arrays of 'name' and separate array of 'description'. I would prefer arrays of 'item' with each array containing a 'name' and a 'description' field. Is there any way to accomplish this without generating the an index in my javascript? Since people can add and remove these dynamically it's very difficult for my javascript to calculate the appropriate index for the next item. Is there no way to do this generically?

推荐答案

不可能做你想做的事,但如果有帮助,这里有一些代码可以将它拼凑起来,我认为它会起作用(使用 item_name[]item_description[]):

It's not possible to do what you want, but if it helps, here's some code to piece it back together that I think will work (with item_name[] and item_description[]):

$items_desc = $_POST["item_description"];
$items_name = $_POST["item_name"];
$items = array();
for ($i = 0; $i < count($items_name); $i++)
{
    $items[] = array("name" => $items_name[$i], "description" => $items_desc[$i]);
}

这篇关于如何在发布到 PHP 的 HTML 表单中使用数组格式的输入字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:57