将ID与输入元素相关联

时间:2020-03-19 19:25:40

标签: javascript php jquery

我想知道什么是实现此目标的最佳方法。我有一个包含两列的表行作为输入。我需要将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>

Table

如果我这样做并提交表格,那么我将得到3个数组:一个用于ID,注释和小时数。如何将ID与相应的注释和时间相关联。还是有更好的方法来做到这一点?

非常感谢您!

enter image description here

编辑***

$count = $_POST['rows'];

for($i = 0; $i < $count; $i++)
{

    echo 'id ' . $_POST['id'][$i] . ' Notes ' . $_POST['notes'][$i] . ' Hours ' . $_POST['hours'][$i] . '<br>';

}

1 个答案:

答案 0 :(得分:0)

鉴于每个“行”的索引都匹配,则可以对其进行循环,然后将它们组合成一个更一致的新数组,如下所示:

$arr = [
    'id' => [
        0 => 123,
        1 => 456,
        2 => 789,
    ],
    'notes' => [
        0 => 'Parent Cancel',
        1 => 'COVID-19',
        2 => 'Parent Cancel',
    ],
    'hours' => [
        0 => 0,
        1 => 1,
        2 => 0,
    ],
];

$newArr = [];
foreach ($arr['id'] as $index => $id) {
    $newArr[$id] = [
            'notes' => $arr['notes'][$index],
            'hours' => $arr['hours'][$index],
    ];
}

var_export($newArr);

输出:

array (
  123 =>
  array (
    'notes' => 'Parent Cancel',
    'hours' => 0,
  ),
  456 =>
  array (
    'notes' => 'COVID-19',
    'hours' => 1,
  ),
  789 =>
  array (
    'notes' => 'Parent Cancel',
    'hours' => 0,
  ),
)

但是请注意,这仅在所有索引始终存在(无间隙)的情况下才有效-当前的HTML就是这种情况。

另一种方法是将ID(整数)作为输入字段中的索引,但是,这仍然会给您留下两个仍然需要组合的数组(一个用于注释,一个用于小时)。因此,它并不能使它变得更简单。