【问题标题】:PHP get post data from inputs with arrays []PHP从带有数组[]的输入中获取发布数据
【发布时间】:2017-04-26 11:50:55
【问题描述】:

我正在创建一个表单,用户可以动态添加额外的字段,每次创建新输入时,它被命名为 accountemails[type],每个组的类型都不同。

我想发布这个表单并检索按类型分组的数据

例如,如果我有 2 个组 - group1 和 group2 我的输入将被命名为:

name="accountemails[group1]"
name="accountemails[group2]"

并且可能有多个具有相同的组名

对于php中的帖子,我试过了

foreach($_POST["accountemails"] as $type => $email) {

}

虽然我会工作,但我可以使用 $type 作为每个组,然后使用 $email 作为每个值,但这仅显示每个组最后发布的输入值

【问题讨论】:

  • var_dump($_POST["accountemails"]) 告诉你什么? ^^
  • 您在foreach 循环中到底在做什么? $_POST["accountemails"] 包含哪些值(参见上面的评论)?
  • 您必须在 HTML 中区分每个数组的字段。见stackoverflow.com/q/9073690/498457
  • 所以我发布了 g1、g2 和 o1 并且 var 转储显示 array(4) { ["general"]=> string(2) "g2" ["orders"]=> string(2) "o1" ["renewals"]=> string(0) "" ["accounts"]=> string(0) "" }

标签: php arrays post


【解决方案1】:

详细说明 Benoti 的 答案,听起来像是在添加新值时覆盖了 $_POST['accountemails'] 数据。将 group 数据添加到数组中。

$_POST['accountemails']['group1'] [] = "Group 1 - 1"; //Emulates html form: name = accountemails[group1][] with value of: Group 1 - 1
$_POST['accountemails']['group1'] [] = "Group 1 - 2"; //Emulates html form: name = accountemails[group1][] with value of: Group 1 - 2

$_POST['accountemails']['group2'] [] = "Group 2 - 1"; //Emulates html form: name = accountemails[group2][] with value of: Group 2 - 1
$_POST['accountemails']['group2'] [] = "Group 2 - 2"; //Emulates html form: name = accountemails[group2][] with value of: Group 2 - 2

foreach ($_POST as $v) {

    foreach ($v['group1'] as $email) {

        echo "Group 1 Email: " . $email;
        echo "<br>";
    }

    foreach ($v['group2'] as $email) {

        echo "Group 2 Email: " . $email;
        echo "<br>";     
    }
}

输出

Group 1 Email: Group 1 - 1
Group 1 Email: Group 1 - 2
Group 2 Email: Group 2 - 1
Group 2 Email: Group 2 - 2

【讨论】:

    【解决方案2】:

    如果要添加多个同名的表单输入,则需要在名称的最后添加双括号。

     name="accountemails[group1][]"
     name="accountemails[group2][]"
    

    然后,如果用户为 group1 添加额外字段,则每个不同组中的每个新帐户电子邮件都将添加到一个数组中,您可以在 foreach 循环中检索该数组。

    【讨论】:

    • 索引(group1/group2)不同,所以使用name="accountemails[group1]"/name="accountemails[group2]"(不带额外的括号)是有效的,并且会将两个字段都提交到$_POST['accountemails']数组中.在末尾添加 [] 时,您实际上是在将其扩大到另一个维度,这不是必需的。
    • @Qirel 但 OP 已声明可能有多个具有相同组名的记录,例如[组1]。所以我猜测 OP 正在尝试将数据添加到 accountemails[group1]accountemails[group2] 的数组中,这意味着上面的答案是正确的,因为此时所有 OP 正在覆盖 ['group1']['group2'] 时已添加新值。
    • @Qirel 澄清一下,我不是想引发战争 :-) 我只是好奇,因为这将是我解决问题的逻辑。显然,如果我错了,那就直截了当。
    • 这是我的表单的样子:s27.postimg.org/fk54dsm6r/… - 所以每个输入都是 accountemails[general][] 和 accountemails[orders][]
    • @Kitson88 谁说过战争? ;-) 我们在这里都很友好!不过,您很可能是对的 - 我想我可能误解了这个问题(并且完全错过了 OP 问题的“可能有多个具有相同组名的人”部分!) .
    猜你喜欢
    • 2018-03-02
    • 2016-06-06
    • 2018-12-31
    • 2018-01-02
    • 2017-12-25
    • 2018-11-09
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多