【问题标题】:How to get array with html same name classes in PHP [duplicate]如何在PHP中获取具有html同名类的数组[重复]
【发布时间】:2021-03-14 17:10:50
【问题描述】:

我是 PHP 新手,但找不到我需要的东西。所以我的问题是我在 HTML 中有 4 个同名的输入,我想在 PHP 中用它们创建一个数组。有没有办法做到这一点?查看下图:Photo of 4 inputs

所以这 4 个输入具有相同的名称,我想获取用户输入的信息并将其插入 HTML 页面,请回答我的问题或推荐更好的方法!

这是我的代码:

   <input class="inputText" type = "text" class="form-control" placeholder="Some text here"/>
   <input class="inputText" type = "text" class="form-control" placeholder="Some text here"/>
   <input class="inputText" type = "text" class="form-control" placeholder="Some text here"/>
   <input class="inputText" type = "text" class="form-control" placeholder="Some text here"/>

【问题讨论】:

  • 你的代码在哪里?
  • 抱歉,我马上编辑
  • 您在此输入中没有name 属性

标签: php html


【解决方案1】:

使用这个:

 <input class="inputText" type = "text" class="form-control" name="text[]" placeholder="Some text here" />
       <input class="inputText" type = "text" class="form-control"  name="text[]"  placeholder="Some text here"/>
       <input class="inputText" type = "text" class="form-control" name="text[]"  placeholder="Some text here"/>
       <input class="inputText" type = "text" class="form-control"  name="text[]"  placeholder="Some text here"/>

那么当你打印 $_POST 时,你会在你的 php 文件中得到“name”数组

【讨论】:

    【解决方案2】:

    您的输入中没有名称,因此您永远不会在 $_POST 中获得值:)。所以,我们添加名称:

    <input name="thing1" value="1" />
    <input name="thing2" value="2" />
    <input name="thing3" value="3" />
    <input name="thing4" value="4" />
    

    现在您可以使用$_POST['thing1']$_POST['thing4']。但是我们希望它们在一个数组中,所以它们需要同名。

    <input name="thing" value="1" />
    <input name="thing" value="2" />
    

    不幸的是,您现在在$_POST['thing'] 中有一个值,即'2'(最后一个覆盖了前一个)。为了告诉 PHP/html 使其成为一个数组,您可以使用与 PHP 中相同的技巧:

    <input name="thing[]" value="1" />
    <input name="thing[]" value="2" />
    <input name="thing[]" value="3" />
    <input name="thing[]" value="4" />
    

    你有 $_POST['thing'] 的值 ['1','2','3','4']

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      相关资源
      最近更新 更多