2016-07-07 55 views
1

我正在尝试使用PHP对具有动态生成的键数的数组进行分组。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]”键。

我用这个来获得标题名称:

// 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; 
    } 
} 

但它不是产生所需格式的数组。

+1

专注于使用MySQL。这并不复杂。 – Henrik

+0

当'Person One'有一个'SkillA'('2015-05-04')和几个'SkillB'和'SkillC'填充值时,它应该如何分组? – RomanPerekhrest

+0

我查询中的ORDER BY和GROUP BY会阻止任何“技能”使用多个值 - 它只获取每个 – DinosaurHunter

回答

0

让我们回到MySQL查询

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

,变革t到您的查询

+0

的最新“技能日期”这是一个有趣的想法,但是max(SkillA)SkillA, max(SkillB)SkillB'需要动态生成,只有我查询中的技能标题。 – DinosaurHunter

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将两个数组合并在一起。