不确定如何很好地表达这个问题,但希望有人能提供帮助...我正在尝试从MySQL数据库中选择数据并将其输出到使用PHP的HTML表中,从而查询中的数据形成列标题和行。我的“预算”表中的数据如下:
我想在行中输出“客户”,在列中输出“周”,并输出“数量”之和作为数据。到目前为止,我有:
<? $q1 = mysqli_query($conn, "SELECT customer, week, sum(qty) AS qty FROM budget GROUP BY week, customer"); ?>
<table>
<thead>
<tr>
<th>Customer</th>
<th>Week</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<? while($row1 = mysqli_fetch_assoc($q1)){ ?>
<tr>
<td><?= $row1['customer']; ?></td>
<td><?= $row1['week']; ?></td>
<td><?= $row1['qty']; ?></td>
</tr>
<? } ?>
</tbody>
</table>
这会产生一个类似于原始MySQL表格式的表,但是我想实现的是:
每周的选择将是动态的,因此我希望在列中选择4或36周,具体取决于他们在表格中的选择。
答案 0 :(得分:1)
使用mysqli_fetch_row
。每行都是一个可以通过索引访问的数组。看起来像:Array ( [0] => A [1] => 1 [2] => 52 ... )
创建一个新的二维数组,如下所示:
$arr["A"] = [
1 => ...
2 => ...
]
PHP
<?php
// $conn = ...
$q1 = mysqli_query($conn, "SELECT customer, week, sum(qty) AS qty FROM budget GROUP BY week, customer");
$res1 = [];
while($row = mysqli_fetch_row($q1))
{
array_push($res1, $row);
}
$title = "Customer";
$max = $res1[count($res1) - 1][1];
$res2 = [];
// Index for "title" ("A", "B", "C", ...)
$i = 0;
foreach ($res1 as $row) {
$res2[$row[$i]][$row[1]] = $row[2];
}
?>
HTML
<table>
<thead>
<tr>
<td><?= $title ?></td>
<?php for ($i = 1; $i <= $max; $i++): ?>
<td><?= $i ?></td>
<?php endfor; ?>
</tr>
</thead>
<tbody>
<?php foreach ($res2 as $key => $values): ?>
<tr>
<td><?= $key ?></td>
<?php foreach ($values as $value): ?>
<td><?= $value ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>