同时使用两个 foreach 函数?



我有一个使用PHP构建的在线应用程序,用于保存多个风险评估。用户可以在 Web 表单中键入标题、日期和签名,选择所需的风险评估,然后按保存。这会将文档保存在服务器上指定的文件夹中,并添加相同的标题、日期等。

但是,我被要求在每个选定的风险评估下实施文本框,以为每个风险评估添加单独的评论。我当前的代码循环遍历每个选定的风险评估,并为每个风险评估添加相同的信息。我现在如何为每个注释添加独特的注释。我假设我需要为此使用另一个 foreach 函数,但我不确定如何去做。

当前代码:

//'files' are the risk assessments selected using checkboxes.
foreach($_POST['files'] as $selected){
$template1 = new PhpOfficePhpWordTemplateProcessor("templates/$selected.docx");
$template1->setValue('fldProject_Title', str_replace('&', '&', $_POST['title']));
$template1->setValue('JobNo', $_POST['JobNo']);
$template1->setValue('fldDatePrep', $_POST['date']);
$template1->setValue('sub', $_POST['sub']);
$filepath1 = "P_DRIVE/$JobNo/$sub/Health and Safety/Risk Assessments/$selected.docx";
$template1->saveAs($filepath1);
}   

只需在那个里面嵌套一个foreach。

foreach($_POST['files'] as $selected){
$template1 = new PhpOfficePhpWordTemplateProcessor("templates/$selected.docx");
$template1->setValue('fldProject_Title', str_replace('&', '&', $_POST['title']));
$template1->setValue('JobNo', $_POST['JobNo']);
$template1->setValue('fldDatePrep', $_POST['date']);
$template1->setValue('sub', $_POST['sub']);
$filepath1 = "P_DRIVE/$JobNo/$sub/Health and Safety/Risk Assessments/$selected.docx";
foreach ($_POST['comments'] as $comment) {
// perform actions
}
$template1->saveAs($filepath1);
}   

我设法为任何感兴趣的人解决了这个问题。

通过将文件数组索引与注释数组索引匹配。

$_POST['files'] = array_values(array_filter($_POST['files']));
foreach($_POST['files'] as $key1 => $selected)
{
$template1 = new PhpOfficePhpWordTemplateProcessor("templates/$selected.docx");
$template1->setValue('fldProject_Title', str_replace('&', '&', $_POST['title']));
$template1->setValue('JobNo', $_POST['JobNo']);
$template1->setValue('fldDatePrep', $_POST['date']);
$template1->setValue('sub', $_POST['sub']);
$notesArray = array_values(array_filter($_POST['notes']));
foreach($notesArray as $key2 => $notes)
{
if($key1 == $key2)
{
$template1->setValue('notes', $notes);
}
}
$filepath1 = "P_DRIVE/$JobNo/$sub/Health and Safety/Risk Assessments/$selected.docx";
$template1->saveAs($filepath1);
}

最新更新