問題描述
我了解使用數組格式的 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 表單中使用數組格式的輸入字段名稱?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!