doushi1960 2019-06-11 16:36
浏览 286

HTML表单中的PHP多维数组

I've got an HTML form that allows a user to submit details about one or more children. Each child can have one or more items.

My HTML form structure looks like this:

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

In my PHP, I'm looking to achieve something like:

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']). 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). 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.

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.

  • 写回答

1条回答 默认 最新

  • dsjhejw3232 2019-06-12 10:05
    关注

    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]">
    
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图