Foreach数据在变量内不起作用



我尝试在变量中使用foreach,但似乎不起作用。我做错了什么?我没看到。

<?php
include("auth.php");
include ("database_connection.php");
$id = (ISSET($_GET['invoice'])) ? intval($_GET['invoice']):0;
$invoiceDatas = $connection->query("SELECT * FROM invoices where id ='$id'")->fetchAll();
$invoiceNotes = $connection->query("SELECT * FROM notes where invoice ='$id'")->fetchAll();

$html = "
<div class='row'>
<?php foreach($invoiceDatas as $invoiceData): ?>
<div><?= $invoiceData['firstname']; ?></div>
<div><?= $invoiceData['lastname']; ?></div>
<?php endforeach; ?>
</div>
<div class='row'>
<?php foreach($invoiceNotes as $invoiceNote): ?>
<div><?= $invoiceNote['note']; ?></div>
<?php endforeach; ?>
</div>
.....not important whats going on after here

我会用不同的方式格式化所有内容,以不同的步骤将字符串附加到html变量:

$html  = "";
$html .= "<div class='row'>";
foreach($invoiceDatas as $invoiceData){
$html .= "<div>$invoiceData['firstname']</div>";
$html .= "<div>$invoiceData['lastname']</div>";
}
$html .= "</div>";
$html .= "<div class='row'>";
foreach($invoiceNotes as $invoiceNote){
$html .= "<div>$invoiceNote['note']</div>";
}
$html .= "</div>";
echo $html;

您可以在当前php文件中使用以下内容将动态生成的内容捕获到变量中:

ob_start();
include __DIR__ . '/invoice_rows.php';
$html = ob_get_clean();

其中invoice_rows.php将包含:

<div class='row'>
<?php foreach ($invoiceDatas as $invoiceData) : ?>
<div><?= $invoiceData['firstname']; ?></div>
<div><?= $invoiceData['lastname']; ?></div>
<?php endforeach; ?>
</div>
<div class='row'>
<?php foreach ($invoiceNotes as $invoiceNote) : ?>
<div><?= $invoiceNote['note']; ?></div>
<?php endforeach; ?>
</div>

最新更新