将 ID 与输入元素相关联

我想知道实现这一目标的最佳方式或方法是什么。我有一个表格行,有两列作为输入。我需要将一个 ID 关联到输入元素,以便在提交表单时我可以识别输入属于哪一行。这就是我所拥有的。


<tr>

    <td><input type="hidden" name="id[]" value="252748"> Tue - Mar 3rd 3:03 PM</td>

    <td>

        <select class="form-control" name="notes[]">

            <option value="Parent Cancel" selected="">Parent Cancel</option>

            <option value="COVID-19">COVID-19</option>

        </select>

    </td>

    <td><input class="form-control" type="tel" name="hours[]" value="0"></td>

</tr>

<tr>

    <td><input type="hidden" name="id[]" value="253081"> Wed - Mar 4th 2:03 PM</td>

    <td>

        <select class="form-control" name="notes[]">

            <option value="Parent Cancel" selected="">Parent Cancel</option>

            <option value="COVID-19">COVID-19</option>

        </select>

    </td>

    <td><input class="form-control" type="tel" name="hours[]" value="0" readonly=""></td>

</tr>

http://img.mukewang.com/6364d6d700013fe305880468.jpg

如果我这样做并提交表单,我将得到 3 个数组:一个用于 id、notes 和 hours。我如何将 ID 与通讯员的注释和时间相关联。还是有更好的方法来做到这一点?



素胚勾勒不出你
浏览 86回答 1
1回答

宝慕林4294392

鉴于每个“行”的索引匹配,您可以循环它们并将它们组合成一个更连贯的新数组,如下所示:$arr = [&nbsp; &nbsp; 'id' => [&nbsp; &nbsp; &nbsp; &nbsp; 0 => 123,&nbsp; &nbsp; &nbsp; &nbsp; 1 => 456,&nbsp; &nbsp; &nbsp; &nbsp; 2 => 789,&nbsp; &nbsp; ],&nbsp; &nbsp; 'notes' => [&nbsp; &nbsp; &nbsp; &nbsp; 0 => 'Parent Cancel',&nbsp; &nbsp; &nbsp; &nbsp; 1 => 'COVID-19',&nbsp; &nbsp; &nbsp; &nbsp; 2 => 'Parent Cancel',&nbsp; &nbsp; ],&nbsp; &nbsp; 'hours' => [&nbsp; &nbsp; &nbsp; &nbsp; 0 => 0,&nbsp; &nbsp; &nbsp; &nbsp; 1 => 1,&nbsp; &nbsp; &nbsp; &nbsp; 2 => 0,&nbsp; &nbsp; ],];$newArr = [];foreach ($arr['id'] as $index => $id) {&nbsp; &nbsp; $newArr[$id] = [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'notes' => $arr['notes'][$index],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'hours' => $arr['hours'][$index],&nbsp; &nbsp; ];}var_export($newArr);输出:array (&nbsp; 123 =>&nbsp; array (&nbsp; &nbsp; 'notes' => 'Parent Cancel',&nbsp; &nbsp; 'hours' => 0,&nbsp; ),&nbsp; 456 =>&nbsp; array (&nbsp; &nbsp; 'notes' => 'COVID-19',&nbsp; &nbsp; 'hours' => 1,&nbsp; ),&nbsp; 789 =>&nbsp; array (&nbsp; &nbsp; 'notes' => 'Parent Cancel',&nbsp; &nbsp; 'hours' => 0,&nbsp; ),)但是请注意,这仅适用于所有索引始终存在(没有间隙) - 您当前的 HTML 应该是这种情况。另一种方法是将 ID(整数)作为输入字段中的索引,但是这仍然会给您留下两个您仍然必须组合的数组(一个用于注释,一个用于小时)。因此,恕我直言,这并不会让它变得更容易。
打开App,查看更多内容
随时随地看视频慕课网APP