And*_*rew 2 php mysql html-table
我有个问题.假设我有一个具有这种结构的关系表"ClientInvoices":
id | id_client | id_invoice 1 1 1 2 1 2 3 2 3 4 3 4 5 1 5
您可以看到CLIENT 1有3张发票.每个客户端都可以有多个发票,我可以提取这些信息并将其放在一个html表中,如下所示:
CLIENT | INVOICES
1
1 2
5
2 3
3 4
我怎样才能做到这一点?我知道很简单,但我觉得我被卡住了.如何计算rowspawn,并且只显示一个包含所有发票的客户?
不错的问题,行数的计算是通过计算发票来完成的.这是我提出的代码:
<?php
/**
* @author Truth
* @copyright 2011
*/
$dsn = "mysql:host=localhost;dbname=test";
$dbc = new PDO($dsn, 'root', 'pass');
$query = 'SELECT * FROM invoice';
$stmt = $dbc->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['client_id']][] = $row['invoice_id'];
}
?>
<!DOCTYPE html>
<html>
<head>
<!-- Metas -->
<meta http-equiv="content-type" content="utf-8" />
<meta name="author" content="Truth" />
<title>Invoice Rowspan Example</title>
</head>
<body>
<table id="invoices" border="1">
<thead>
<th>Client</th>
<th>Invoices</th>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo "<td>$invoice</td>";
echo "</tr>";
$count++;
}
}
?>
</tbody>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这会根据您的需要生成一个表.如果您有什么不明白的地方,请发表评论,我会解释