PHP - 按动态数量的键组数组

时间:2016-07-07 11:33:31

标签: 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数组分组的问题"但似乎没有人能做到我需要的东西。问题是数组键是动态生成的。它们将始终包含[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;
    }
}

但它没有以所需的格式生成数组。

2 个答案:

答案 0 :(得分:0)

让我们回到MySQL查询

select employee, max(SkillA) SkillA, max(SkillB) SkillB 
from t 
group by employee

t更改为您的查询

答案 1 :(得分:0)

由于每人的ID相同,为什么不将它用作数组键?

$query = your_database_query;

$aQueryResult = array ( );

while ( $aFetch = mysql_fetch_assoc ( $query ) )
{
    if ( isset ( $aQueryResult[$aFetch['id']] ) )
    {
        $aQueryResult[$aFetch['id']] = array_merge ( array_filter ( $aQueryResult[$aFetch['id']] ), array_filter ( $aFetch ) );
    }
    else
    {
        $aQueryResult[$aFetch['id']] = $aFetch;
    }
}

print_r ( $aQueryResult );

这样,你拥有多少技能领域并不重要。

修改 array_filter删除NULL值,array_merge将两个数组合并在一起。