对查询结果集中的两列数据进行透视和计数

问题描述 投票:0回答:1

我有这个数据:

array (size=42)
  0 => 
    array (size=6)
      'Id' => string '1' 
      0 => string '1' 
      'Group' => string 'A' 
      1 => string 'A' 
      'Sport' => string 'Tennis' 
      2 => string 'Tennis' 
  1 => 
    array (size=6)
      'Id' => string '2' 
      0 => string '2' 
      'Group' => string 'B' 
      1 => string 'B' 
      'Sport' => string 'Foot' 
      2 => string 'Foot' 

...

下面更易读:

身份证 团体 运动
1 A 网球
2 B
3 D 网球
4 A 自行车

我不知道我的列表中有多少运动,但我知道我有 4 组(A-B-C-D)。

我需要知道每个运动项目的每个组有多少名运动员,以及每个组的总数。 我想用 PHP 来制作这种格式。

运动 A组 B组 C组 D组
网球 1 0 0 1
0 1 0 0
自行车 1 0 0 0
总计 2 1 0 1
php mysql arrays count pivot
1个回答
0
投票

如果您从第一个表中有这样的数据:

$data = [
    ['Id' => '1', 'Group' => 'A', 'Sport' => 'Tennis'],
    ['Id' => '2', 'Group' => 'B', 'Sport' => 'Foot'],
    ['Id' => '3', 'Group' => 'D', 'Sport' => 'Tennis'],
    ['Id' => '4', 'Group' => 'A', 'Sport' => 'Bike'],
];

我初始化了一个关联数组 $counts 来保存每个运动和组的计数,并初始化了 $totalCounts 来保存每个组的总计数

$counts = [];
$totalCounts = ['A' => 0, 'B' => 0, 'C' => 0, 'D' => 0];

迭代原始数据数组以填充 $counts 和 $totalCounts 以计算出现次数

foreach ($data as $entry) {
    $group = $entry['Group'];
    $sport = $entry['Sport'];

    if (!isset($counts[$sport])) {
        $counts[$sport] = ['A' => 0, 'B' => 0, 'C' => 0, 'D' => 0];
    }

    $counts[$sport][$group]++;
    $totalCounts[$group]++;
}

显示表格

echo "Sport\tGroup A\tGroup B\tGroup C\tGroup D\n";
foreach ($counts as $sport => $groupCounts) {
    echo "{$sport}\t{$groupCounts['A']}\t{$groupCounts['B']}\t{$groupCounts['C']}\t{$groupCounts['D']}\n";
}
echo "Total\t{$totalCounts['A']}\t{$totalCounts['B']}\t{$totalCounts['C']}\t{$totalCounts['D']}\n";

但我更喜欢先在 html 中实现类似的内容

    <table border="1">
    <tr>
        <th>Sport</th>
        <th>Group A</th>
        <th>Group B</th>
        <th>Group C</th>
        <th>Group D</th>
    </tr>
    <?php foreach ($counts as $sport => $groupCounts): ?>
        <tr>
            <td><?php echo $sport; ?></td>
            <td><?php echo $groupCounts['A']; ?></td>
            <td><?php echo $groupCounts['B']; ?></td>
            <td><?php echo $groupCounts['C']; ?></td>
            <td><?php echo $groupCounts['D']; ?></td>
        </tr>
    <?php endforeach; ?>
    <tr>
        <td>Total</td>
        <td><?php echo $totalCounts['A']; ?></td>
        <td><?php echo $totalCounts['B']; ?></td>
        <td><?php echo $totalCounts['C']; ?></td>
        <td><?php echo $totalCounts['D']; ?></td>
    </tr>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.