来处理PHP表单域的动态量的最佳方式?(Best way to handle dynamic amo

2019-08-19 15:16发布

我有一个系统,我需要列出员工任意数量与那里的“工作时间”可输入值的一周中每天一个文本框。

所以,我需要生成行的动态数量的表格,每一行也会包含7个文本字段。 我只是想知道什么是分配的ID时,这些字段可以很容易地遍历一次,我收到我的后端的输入数据使用的最佳惯例?

每一行都将与代表雇员的ID行相关的ID号。

这将是真棒,能够做一些事情,如:

foreach($rows as $row)
{
     $id = $row['id'];

     $employee = Employee::find($id);

     foreach($row['hoursWorked'] as $dailyHours)
     {
           $timecard = new Timecard();
           $timecard->hours = $dailyHours;
           $employee->timecards->insert($timecard);
     }
}

什么是组织我的HTML侧形式和ID我的投入,使这个尽可能无痛的最佳方式?

一点题外话,我在情况下,Laravel 3框架,开辟了任何其他解决方案中的工作。

Answer 1:

<input type="text" name="hoursWorked[]" />将在内部转换为下一个数组$_POST['hoursWorked'] 。 这意味着你可以做这样的事情:

<input type="text" name="hoursWorked[12345][]" /> <!-- Sunday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Monday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Tuesday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Wednesday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Thursday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Friday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Saturday -->

然后,在PHP:

<?php
foreach ($_POST['hoursWorked'] as $employeeId=>$dayArray) {
    foreach ($dayArray as $dayOfWeek=>$hoursWorked) {
        // $employeeId will be 12345
        // $dayOfWeek will be 0, 1, 2, 3, 4, 5 ,6
        // $hoursWorked will be the value of the text field
    }
}


Answer 2:

我从来没有使用Laravel框架,但总体上我这样做在PHP中:

foreach ($employee as $key=>$e) {
   echo '<input type="text" name="hours[]" id="hours_'.$key.'" value="'.$e.'" />';
}

这样,您将有时间值在后一个数组,你可以通过ID如果需要引用相应的字段。 第一场将有ID =“HOURS_1”等。另外,如果你不想使用$键从查询,你可以这样做:

$cntr = 1;
foreach ($employee as $e) {
   echo '<input type="text" name="hours[]" id="hours_'.$cntr.'" value="'.$e.'" />';
   $cntr++;
}

当你捕捉到POST的值,您将有值的数组$_POST['hours'] 请记住,这是一个从零开始的数组,但你可以使用foreach循环通过值进行迭代。



文章来源: Best way to handle dynamic amount of form fields in PHP?