2012-02-03 61 views
1

我有一堆看起来像这样的PHP数组(请不要问为什么,我只是在做我的工作......我只会说EAV ... ):在ID密钥上高效地组合多个关联数组

$firstNames = ([accountId] => 100, [firstName] => 'John' 
       [accountId] => 101, [firstName] => 'Fred'); 


$lastNames = ([accountId] => 100, [lastName] => 'Doe' 
       [accountId] => 101, [lastName] => 'Bloggs'); 


$city  = ([accountId] => 100, [city] => 'New York' 
       [accountId] => 101, [city] => 'Cambridge'); 


$country = ([accountId] => 100, [country] => 'USA' 
       [accountId] => 101, [country] => 'UK'); 

等等等等

我将它们组合成一个阵列:

$userDetails = ([accountId] => 100, [firstName] => "John", [lastName] => "Doe", 
       [city] => "New York", [country] => "USA"); 

我的感觉是正确的答案应该是打破这些属性进行EAV和它们建模正确。但我不能。也可以在数据库中进行自连接时进行自连接,但我简化了示例,这并不是真的可行 - 而且我被告知要这样做......可能会有一堆以后还会加入其他领域。

那么什么是最好的方式来产生一个关联数组,合并accountId在PHP中?是否有一个功能,或者我需要循环打转等

+0

恐怕你将不得不使用5'的foreach '循环,你能做到吗或者你需要代码示例? – Vyktor 2012-02-03 12:32:54

回答

2

此嵌套foreach应该这样做:

$result = array(); 

foreach (array('firstNames' => 'firstName', 'lastNames' => 'lastName', 'city' => 'city', 'country' => 'country') as $srcArr => $arrKey) { 
    foreach ($$srcArr as $item) { 
    if (!isset($result[$item['accountId']])) { 
     $result[$item['accountId']] = $item; 
    } else { 
     $result[$item['accountId']][$arrKey] = $item[$arrKey]; 
    } 
    } 
} 

var_dump($result); 

See it working

+1

你缺少'$ result [$ item ['accountId']]'初始化,并且你看看'$ userDetails',这不应该工作:)你介意我是否可以接受你的答案并修复你的错误? :) – Vyktor 2012-02-03 12:37:30

+0

@Vyktor固定和绝对工作,请参阅键盘的链接:-) – DaveRandom 2012-02-03 12:42:41

+0

真棒 - 非常感谢你们的快速答案 – 2012-02-03 12:44:32