PHP:如何在字符串中连接 foreach?

PHP: How do I concatenate a foreach inside a string?

我想使用 MPDF 的库创建一个 PDF 生成器。在我在 PDF 生成器中创建的 table 中(当然使用 HTML),我想执行一个 foreach() 循环。 这是我的代码:

$html = '<td style="border: 1px solid black; border-collapse: collapse;">
    // Here I want foreach concatenation
</td>
<td style="border: 1px solid black; border-collapse: collapse;">
    // Here I want foreach concatenation                                
</td>
<td style="border: 1px solid black; border-collapse: collapse;">
    // Here I want foreach concatenation                                
';

我尝试对变量使用常规技术。 ('.$var.'),但这没有成功。 我也试过匿名函数...

            $PDFFunction = 
                function($arr) {
                    foreach($arr as $key) {
                       // And now somewhere, i've got to return the $key... But I tried in the foreach loop and outside the loop...
                    }
                };

正如您在我的评论中看到的那样,我不知道应该将 return() 函数放在哪里。 当我把它放在循环中时,它只显示第一个键,当我把它放在循环外(但在函数内)时,我只得到最后一个键...... 有谁知道解决这个问题的方法吗?

谨致问候...

尚不完全清楚您在 PDF 中 "want to concatenate" 的内容,但您可以在构建文档时直接在文档中执行此操作。下面包含的是 $html 变量的一部分,其中包含 foreach 循环,具体取决于您对要执行的操作的描述。

$html = '</tr>
          <tr>
              <td style="border: 1px solid black; border-collapse: collapse;">';

foreach($arr as $key) {
    $html .= $key;
}

$html .= '</td> 
          <td style="border: 1px solid black; border-collapse: collapse;">';
foreach($arr as $key) {
    $html .= $key;
}
$html .= '</td> 
          <td style="border: 1px solid black; border-collapse: collapse;">';
foreach($arr as $key) {
    $html .= $key;
}
$html .= '</td>';