【问题标题】:How to format the name of inputs which belong in group如何格式化属于组的输入的名称
【发布时间】:2018-02-08 03:13:42
【问题描述】:

对不起,如果标题令人困惑,请尽力描述我的问题。

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

例如,当使用复选框时,我知道使用括号将它们放入一个数组中(通过 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][]"/>

以上都没有体现在我上面进一步提到的结构中。

如何使$_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
    )

)

谢谢。

【问题讨论】:

  • 1号变种有什么问题?
  • @u_mulder 我已经更新了我的问题以显示变体 1 产生了什么(print_r-ing $_POST['people']

标签: php html-input


【解决方案1】:

您必须明确设置索引来分组项目。在您的情况下,它将是:

<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 -->

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多