在ID密钥上有效地组合多个关联数组

时间:2012-02-03 12:28:44

标签: php entity-attribute-value

我有一堆看起来像这样的php数组(请不要问为什么,我只是在做我的工作......我只会说是EAV ......):

$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中打破并正确建模。但我不能。在db中自我加入也可以自我加入,但我已经简化了示例,这实际上是不可能的 - 而且我被告知要这样做......可能会有一堆其他字段也随后加上了。

那么在PHP中使用accountId合并生成一个关联数组的最佳方法是什么?有功能,还是我需要循环回转等。

1 个答案:

答案 0 :(得分: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

相关问题