如何格式化属于组的输入名称

How to format the name of inputs which belong in group

抱歉这个标题令人困惑,我已尽力描述我的问题。

所以我有一些输入,在一个表单中,我想 'group' 在一起,因为它们是同一实体的一部分。

我知道使用方括号将它们放入一个数组中(PHP),例如在使用复选框时,但我的情况有点不同。

我有一个 person 的 3 个输入,在表格中,可以有多个 people.

这就是如果我只有一个人的形式:

<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
<input type="text" name="email"/>

但是,我需要允许多个 people 并且我希望它们全部通过 PHP 中的一个数组,如下所示:

// print_r($_POST['people']);
array(
   [0] => array(
        'first_name'=>'john'
        'last_name' => 'smith'
        'email'=>'john.smith@example.com'
      )
   [1] => array(
        'first_name'=>'john2'
        'last_name' => 'smith2'
        'email'=>'john.smith@example.com2'
      )
 )

我试过(1):

<input type="text" name="people[][first_name]"/>
<input type="text" name="people[][last_name]"/>
<input type="text" name="people[][email]"/>

我试过了 (2):

 <input type="text" name="people[first_name][]"/>
 <input type="text" name="people[last_name][]"/>
 <input type="text" name="people[email][]"/>

我试过了 (3):

 <input type="text" name="people[][first_name][]"/>
 <input type="text" name="people[][last_name][]"/>
 <input type="text" name="people[][email][]"/>
以上的

None 都在我上面提到的结构中。

如何使 $_POST['people'] 看起来像上面显示的数组?

编辑:

这是 (1) 产生的结果:

Array
(
 [0] => Array
    (
        [first_name] => john
    )

[1] => Array
    (
        [last_name] => smith
    )

[2] => Array
    (
        [email] => john.smith@example.com
    )

[3] => Array
    (
        [first_name] => john2
    )

[4] => Array
    (
        [last_name] => smith2
    )

[5] => Array
    (
        [email] => john.smith@example.com2
    )

)

谢谢。

您必须明确地设置索引以对项目进行分组。在你的情况下它将是:

<form method="POST" action="">
    <input type="text" name="people[0][first_name]"/>
    <input type="text" name="people[0][last_name]"/>
    <input type="text" name="people[0][email]"/>
    <hr />

    <input type="text" name="people[1][first_name]"/>
    <input type="text" name="people[1][last_name]"/>
    <input type="text" name="people[1][email]"/>
    <hr />

    <input type="text" name="people[2][first_name]"/>
    <input type="text" name="people[2][last_name]"/>
    <input type="text" name="people[2][email]"/>
    <hr />

    <input type="submit" name="" value="" />
</form>

并且在 javascript 添加新字段的情况下,它们的名称也应该带有显式索引:

name="people[4][email]"
name="people[5][email]"
<!-- etc -->