简体   繁体   English

HTML表单中的PHP多维数组

[英]PHP multidimensional array from HTML form

I've got an HTML form that allows a user to submit details about one or more children. 我有一个HTML表单,允许用户提交有关一个或多个孩子的详细信息。 Each child can have one or more items. 每个孩子可以有一个或多个项目。

My HTML form structure looks like this: 我的HTML表单结构如下所示:

<input type="text" name="child[1][name]">
<input type="text" name="child[1][dob]">

I then have a table display for the items (as there are 2 fields per item) where the user can add/remove rows via Javascript. 然后我有一个表格显示项目(因为每个项目有2个字段),用户可以通过Javascript添加/删除行。 Example: 例:

<table>
  <tr>
    <td><input type="text" name="child[1][item][name]"></td>
    <td><input type="text" name="child[1][item][value]"></td>
  </tr>
</table>

When I access this data, I'm inputting the child data into a table, then I need to access the items per child separately, so they can be stored in an 'items' table (with the child ID which I'll grab from the database insert). 当我访问这些数据时,我将子数据输入到表格中,然后我需要分别访问每个孩子的项目,这样它们就可以存储在“项目”表中(我将从中获取子项ID)数据库插入)。

In my PHP, I'm looking to achieve something like: 在我的PHP中,我希望实现以下目标:

foreach($_POST['child'] as $child) {

  $child_name = $child['name'];
  $child_dob  = $child['dob'];

  // insert child data to children table

  foreach($_POST['item'] as $item) {

    $item_name  = $item['name'];
    $item_value = $item['value'];

    // insert item data to items table

  }

}

My problem is that without the items, the child array looks fine when I print_r($_POST['child']). 我的问题是没有这些项目,当我print_r($ _ POST ['child'])时,子数组看起来很好。 However when I include the items as per my HTML above, the array only outputs the last item added (whether there is one or more). 但是,当我按照上面的HTML包含项目时,数组只输出添加的最后一项(是否有一个或多个)。 I'm not sure if I'm correctly specifying the array for items in the input tags, or how I should then access in the PHP. 我不确定我是否正确地为输入标签中的项目指定数组,或者我应该如何在PHP中访问。

If anyone has any suggestions about where my syntax may be wrong, or if perhaps I'm approaching this in the wrong way, that would be much appreciated. 如果有人对我的语法可能出错的地方有任何建议,或者如果我可能以错误的方式接近这一点,那将非常感激。

Figured this out. 想出这个。

As suspected, the naming format was wrong for the item input fields, meaning the sub array for items wasn't being posted correctly. 可疑,项目输入字段的命名格式错误,这意味着项目的子数组未正确发布。

Updated to: 更新至:

<input type="text" name="child[1][item][1][name]">
<input type="text" name="child[1][item][1][value]">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM