Php 用MySQL数据填充HTML表的列和行

Php 用MySQL数据填充HTML表的列和行,php,html,mysqli,html-table,Php,Html,Mysqli,Html Table,不知道该如何表达这个问题,但希望有人能帮忙。。。我试图从MySQL数据库中选择数据,并使用PHP将其输出到HTML表中,通过PHP,来自查询的数据形成列标题和行。我的“预算”表中的数据如下所示: 我想输出行中的客户、列中的周和数量之和作为数据。到目前为止,我已经: <? $q1 = mysqli_query($conn, "SELECT customer, week, sum(qty) AS qty FROM budget GROUP BY week, customer&quo

不知道该如何表达这个问题,但希望有人能帮忙。。。我试图从MySQL数据库中选择数据,并使用PHP将其输出到HTML表中,通过PHP,来自查询的数据形成列标题和行。我的“预算”表中的数据如下所示:

我想输出行中的客户、列中的周和数量之和作为数据。到目前为止,我已经:

<? $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周,具体取决于它们在表单中的选择。

With
mysqli\u fetch\u 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>