我正在尝试使用 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 数组分组”有很多 SO 问题,但似乎没有一个能满足我的需要。问题是数组键是动态生成的。它们将始终包含 [id]
、[employee]
,但后面跟着数量不确定的“[skill]
”键。
我用它来获取 header 的名称:
// 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查询
select employee, max(SkillA) SkillA, max(SkillB) SkillB
from t
group by employee
将 t
更改为您的查询
关于PHP - 按动态键数对数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38244394/