创建多个选择字段的数组

时间:2017-01-02 07:04:07

标签: php jquery

我正在开发一个项目,我必须在其中创建一个用户角色系统。几乎已经完成但最后我必须在数据库中添加路由和用户权限,我得到了一个数组

[route] => Array
    (
        [0] => api/user
        [1] => members
    )

[assess] => Array
    (
        [0] => read
        [1] => write
        [2] => read
        [3] => delete
    )

但我需要的是获得像

这样的数组
[0](
    [route] => Array
        (
            [0] => api/user
        )
    [assess] => Array
        (
            [0] => read
            [1] => write
        )
)
[1](
    [route] => Array
        (
            [0] => members
        )
    [assess] => Array
        (
            [0] => read
        )
);

这是我的HTML代码:

<tbody class="tbody">
    <tr class="gradeX">
      <td>
      <select name="route[]">
        <?php $routeCollection = Route::getRoutes();
          foreach ($routeCollection as $value) {
              echo '<option value="'.$value->getPath().'">'.$value->getPath().'</option>';
          } ?>
        </select>
        </td>
        <td><input type="checkbox" value="read" name="check[]"></td>
        <td><input type="checkbox" value="write" name="check[]"></td>
        <td><input type="checkbox" value="delete" name="check[]"></td>
        <td><a href="javascript:;" style="padding: 3px 9px;" class="remove">Delete</a></td>
        <div class="add-row" style="float: right;border: 1px dashed grey;border-radius:5px;border-bottom: 0px;">
            <a href="javascript:;" style="padding: 3px 9px;"><span class="add">Add New</span></a>
        </div>
    </tr>
  </tbody>

1 个答案:

答案 0 :(得分:0)

由于在表单提交时仅提交了选中的复选框,并将复选框链接到您的选择,请为所有名称数组属性添加key值 -

<tbody class="tbody">
    <tr class="gradeX">
      <td>
      <select name="route[0]">
        <?php $routeCollection = Route::getRoutes();
          foreach ($routeCollection as $value) {
              echo '<option value="'.$value->getPath().'">'.$value->getPath().'</option>';
          } ?>
        </select>
        </td>
        <td><input type="checkbox" value="read" name="check[0][]"></td>
        <td><input type="checkbox" value="write" name="check[0][]"></td>
        <td><input type="checkbox" value="delete" name="check[0][]"></td>
        <td><a href="javascript:;" style="padding: 3px 9px;" class="remove">Delete</a></td>
        <div class="add-row" style="float: right;border: 1px dashed grey;border-radius:5px;border-bottom: 0px;">
            <a href="javascript:;" style="padding: 3px 9px;"><span class="add">Add New</span></a>
        </div>
    </tr>
  </tbody>

您需要在javascript代码中增加“添加新内容”中的密钥才能使其正常工作

然后在php中,您可以使用key链接来循环您的值,即。

$array = [];
foreach($_POST['route'] as $key => $value){
    $array[] = array("route" => array($_POST['route'][$key]), // this is the route value, ie. api/user or members
                     "assess" => array($_POST['check'][$key]) //this is the check array, ie. read, write or read
               );
}