Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在ID键上有效组合多个关联数组_Php_Entity Attribute Value - Fatal编程技术网

Php 在ID键上有效组合多个关联数组

Php 在ID键上有效组合多个关联数组,php,entity-attribute-value,Php,Entity Attribute Value,我有一堆php数组,看起来像这样(请不要问为什么,我只是在做我的工作…我要说的是EAV…): 等等 我必须将它们组合成一个阵列: $userDetails = ([accountId] => 100, [firstName] => "John", [lastName] => "Doe", [city] => "New York", [country] => "USA"); 我的感觉是,正确的答案是将这些属性从EAV中分离出来,

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

等等

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

$userDetails =  ([accountId] => 100, [firstName] => "John", [lastName] => "Doe", 
                 [city] => "New York", [country] => "USA");
我的感觉是,正确的答案是将这些属性从EAV中分离出来,并对它们进行正确的建模。但我不能。也可以在db中进行一次又一次的自连接,但我已经简化了示例,这实际上是不可能的-我被告知要这样做…稍后可能还会附加一些字段


那么,在PHP中,在accountId上合并一个关联数组的最佳方法是什么呢?是否有函数,或者是否需要循环循环等。

此嵌套的
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);

我担心您将不得不使用5个
foreach
循环,您可以这样做还是需要代码示例?您缺少
$result[$item['accountId']]]
初始化,请查看
$userDetails
,这不应该起作用:)您介意我回答您的问题并修复您的错误吗?:)太棒了-非常感谢你们两位的快速反应answer@DaveRandom啊,我的坏:)我没有意识到,
$userDetail
是输出,而不仅仅是另一个输入数组。但是我仍然不喜欢
isset($result[$item['accountId']]['accountId'])
,我会选择:
如果(!isset($result[$item['accountId']]){$result[$item['accountId']]=$item;}或者{$result[$item[$accountId']][$arrKey]=$item[$arrKey]];}
@Vyktor,那就行了,我想,从风险值初始化的角度来看,这更有意义。我对PHP数组很懒惰,因为只要将主变量初始化为数组,它就不会抱怨递归级别的创建—您可以执行
$myVar=array()$myVar['level1']['level2']['level3']='value'它不会抱怨,但实际上应该首先初始化内部级别。我将编辑我的答案。@DaveRandom现在它值+1:)我认为在这里放置完美的代码是值得的,也许谷歌查询最终会出现在stackowerflow上。)
$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);