将动态输入索引到其他动态输入数组


Index dynamic input to others dynamic input array

我有一个表单,其中包含动态创建的输入,如下所示(简化):我可以使用"添加人员"按钮创建更多人。对于每个人,我可以添加更多的爱好。

JavaScript:

$(document).ready(function(){
  $(".add_person").click(function(){
    var new_fieldset = $(".person:first").clone();
    $(".person:last").after(new_fieldset);
  });
  $(".add_hobby").click(function(){
    var new_input = '<input type="text" name="hobby[]" />';
    $("this").closest("fieldset").find("div_hobbies").append(new_input);
  });
});

.php:

<fieldset class="person">
<input name="name[]" value="">
<div class="div_hobbies"></div>
<a class="add_hobby">ADD HOBBY</a>
</fieldset>
<a class="add_person">ADD PERSON</a>

我想用方法 POST 发布结果并检索一个数组,但我不知道如何与正确的人索引爱好(有些人可能有 0 个爱好):

我想要的例子:

John with hobbies "FISHING", "DIVING"
Carl with no hobbies
Eddy with hobby "SINGING"
Paul with hobbies "RUNNING", "DIVING", "CYCLING"

var_dump($_POST["名称"])

array(4) {
[0] => string "John",
[1] => string "Carl",
[2] => string "Eddy",
[3] => string "Paul)
}

但是使用 var_dump($_POST['hobby']),我得到一个这样的数组:

    array(6) {
        [0] => string "FISHING",
        [1] => string "DIVING",
        [2] => string "SINGING",
        [3] => string "RUNNING",
        [4] => string "DIVING",
        [5] => string "CYCLING"
        }

我怎样才能与正确的人索引爱好?

这可以通过在代码中添加更多的javascript来实现。解决方案是使您的爱好输入字段名称成为二维数组。

<input type="text" name="hobby[][]" />

提交表单时,请使用 javascript 逻辑循环访问元素,并将 hobby[][] 的第一个索引作为人名。例如,应用 JS 逻辑后,表单元素应该是,

<input type="text" name="hobby[jack][]" />
<input type="text" name="hobby[jack][]" />
<input type="text" name="hobby[rose][]" />
<input type="text" name="hobby[rose][]" />

现在提交表单,在PHP页面中,您将得到一个二维数组,其中第一级键是人名和他们的爱好。