【发布时间】:2016-07-07 11:33:30
【问题描述】:
我正在尝试使用 PHP 对具有动态生成的键数的数组进行分组。
我的查询输出如下内容:
| employee | SkillA | SkillB |
------------+------------+------------
| Person One | 2015-05-04 | - |
| Person One | - | 2016-05-01 |
| Person Two | - | 2016-03-25 |
| Person Two | 2016-04-04 | - |
它是由如下所示的数组构建的:
Array (
[0] => Array (
[id] => 1001675
[employee] => Person One
[SkillA] => 2015-05-04
[SkillB] => NULL
)
[1] => Array (
[id] => 1001675
[employee] => Person One
[SkillA] => NULL
[SkillB] => 2016-05-01
)
[2] => Array (
[id] => 1006111
[employee] => Person Two
[SkillA] => NULL
[SkillB] => 2016-03-25
)
[3] => Array (
[id] => 1006111
[employee] => Person Two
[SkillA] => 2016-04-04
[SkillB] => NULL
)
)
但我需要显示这个:
| employee | SkillA | SkillB |
------------+------------+------------
| Person One | 2015-05-04 | 2016-05-01 |
| Person Two | 2016-04-04 | 2016-03-25 |
这意味着我的数组需要如下所示:
Array (
[0] => Array (
[id] => 1001675
[employee] => Person One
[SkillA] => 2015-05-04
[SkillB] => 2016-05-01
)
[1] => Array (
[id] => 1006111
[employee] => Person Two
[SkillA] => 2016-04-0
[SkillB] => 2016-03-25
)
)
我尝试通过在 MySQL 中使用 GROUP BY 来做到这一点(请参阅这个问题 MySQL - Dynamic Pivot Table Grouping Issue)。但是失败了,我决定尝试与 PHP 组合。
关于“PHP 数组分组”有很多这样的问题,但似乎没有一个完全符合我的需要。问题是数组键是动态生成的。它们将始终包含[id]、[employee],但后面跟着数量不定的“[skill]”键。
我用它来获取标题的名称:
// We don't know the names of the headers
// so loop through all of the array keys to get them
$headers = array();
while ($key = current($data[0])) {
$header = key($data[0]);
array_push($headers, $header); // add the header to an array for later use
echo '<th>' . $header . '</th>'; // write the headers to the table
next($data[0]);
}
所以我想我可以做这样的事情来获取我需要的数据:
$arr = array();
foreach ($data as $key => $item) {
foreach ($headers as $header) {
$arr[$item['employee']][$header] = $item;
}
}
但它没有生成所需格式的数组。
【问题讨论】:
-
专注于使用 MySQL。没那么复杂。
-
当
Person One包含三个记录,其中一个SkillA(2015-05-04) 和多个SkillB和SkillC填充值时,它应该如何分组? -
我的查询中的
ORDER BY和GROUP BY将阻止任何“技能”的多个值 - 它只会获取每个值的最新“技能日期”