【问题标题】:PHP HTML data formatPHP HTML 数据格式
【发布时间】:2016-01-11 23:33:31
【问题描述】:

如何处理这种类型的输入表单:

<form action="update" method="post">
    <table>
        <tr>
            <th>First name</th>
            <th>Last name</th>
        </tr>
        <tr>
            <td><input type="text" name="people[][firstname]" value="John" /></td>
            <td><input type="text" name="people[][surname]" value="Smith" /></td>
        </tr>
        <tr>
            <td><input type="text" name="people[][firstname]" value="Adam" /></td>
            <td><input type="text" name="people[][surname]" value="Boralsky" /></td>
        </tr>
    </table>
</form>

我希望收到一个多维数组,但我收到的是这个:

array (size=4)
  0 => 
    array (size=1)
      'firstname' => string 'John' (length=4)
  1 => 
    array (size=1)
      'surname' => string 'Smith' (length=5)
  2 => 
    array (size=1)
      'firstname' => string 'Adam' (length=4)
  3 => 
    array (size=1)
      'surname' => string 'Boralsky' (length=8)

有人见过这种格式吗?

【问题讨论】:

  • 用索引代替people[0][firstname]people[0][surname]等等,,
  • 好像是一个PHP数组。你在哪里收到这个?你是如何打印这个数组的?您如何尝试访问数组中的这些值?

标签: php html symfony


【解决方案1】:

发生这种情况是因为这实际上是您要求 PHP 做的事情。 [] 是“下一个数组索引”运算符,因此当 PHP 处理输入时,它会看到 people[][firstname] = John,将其理解为“添加到 $people[] = ['firstname' => 'John']”,然后你会得到:

$people = [
    ['firstname' => 'John'],
];

然后,当我们得到 people[][surname] = Smith 时,“添加到 $people[] = ['surname' => 'Smith']”。然后给我们:

$people = [
    ['firstname' => 'John'],
    ['Surname' => 'Smith'],
];

等等。

您需要做的是在您的 html 中显式设置一个数组键。如果这是表单中的唯一人员,则不要使用 people[],而是使用 people[0]。如果有多个人,那么您将不得不为每个人的公共字段动态生成一个索引。

【讨论】:

  • 优胜者!先生写得好。
猜你喜欢
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多