PHP - 按动态键数对数组进行分组

标签 php mysql arrays

我正在尝试使用 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/

相关文章:

javascript - JS二维数组错误: "TypeError: Cannot read property ' 0' of undefined"

mysql - 我可以要求 MySQL 进行 "double"搜索吗?

java - 如何从某个位置开始迭代二维数组?

c++ - 如何拥有灵活的嵌套初始化器?

php - laravel : it cannot find a request that i just created 中的反射异常

java - 选择从 MySql 到 Java 的多列

mysql - 错误 org.hibernate.MappingException : No Dialect mapping for JDBC type: -1

php - 获取 MySQL 数据库中的项目数

php - 如何更改推送通知声音?

php - 检查错误和抛出异常有多远?