php 从MySQL结果集中透视数据

xt0899hw  于 2023-05-16  发布在  PHP
关注(0)|答案(1)|浏览(94)

MySQL数据库结果集:

Department     Month      Value
Sale        February       50
Sale        March          35
Sale        April          65
Sale        May            120
Dispatch   February       85
Dispatch   March          23
Dispatch   April          45
Dispatch   May            33
.... etc

这是重复的所有四个部门。
我想让PHP格式化数据结果,所以看起来像这样:

['Month',   'Sales',  'Dispatch',   'Support', 'Calibration'],
['February', 50,     85,         15,      53],
['March',    35,     23,         12,      55],

等等
MySQL语句:

$sql_line_chart = "SELECT d.department as department, MONTHNAME(date_created) AS month, 
               COALESCE(SUM(CASE WHEN c.cat_id IN (5,6,7,8,9,10,11,12,13,15) THEN time_spent END), 0) as value
                FROM master AS m 
                 INNER JOIN category AS c ON c.cat_id = m.cat_id 
                  INNER JOIN department AS d ON d.dept_id = m.dept_id 
                  WHERE 
                  AND 
                  date_created > CURRENT_DATE - INTERVAL DAYOFYEAR(CURRENT_DATE) - 1 DAY 
                 AND  
                date_created < CURRENT_DATE - INTERVAL DAYOFYEAR(CURRENT_DATE) - 1 DAY + INTERVAL 1 YEAR 
               GROUP BY d.department, month 
              ORDER by d.department ASC, m.date_created ASC";
q8l4jmvw

q8l4jmvw1#

通过迭代查询结果来透视数据,并建立一个新的2d数组。
为新行指定键很重要,否则值可能会写入错误的列。
代码:(Demo

$columns = ['Sale', 'Dispatch', 'Support', 'Calibration'];
$columnLookup = array_flip($columns);
$result = [];
foreach ($array as $row) {
    $rowKey = $row['month'];
    $colKey = $columnLookup[$row['department']];
    $result[$rowKey][$colKey] = $row['value'];
}

一旦你有了$result,就有很多方法可以将数据呈现为HTML。这里有一个基本/简单的方法来循环和输出数据,而不需要HTML:

foreach ($result as $month => $colVals) {
    printf(
        "%' 10s\t%d\t%d\t%d\t%d\n",
        $month,
        $colVals[0] ?? 0,
        $colVals[1] ?? 0,
        $colVals[2] ?? 0,
        $colVals[3] ?? 0
    );
}

输出:

February  50  85  0   0
     March  35  23  0   0
     April  65  45  0   0
       May  120 33  0   0

相关问题