如何使用唯一键递归合并数组?

How can I merge array recursively with a unique key?

我这样创建数组:

foreach ($array as $key => $value) {
          $array1[$value->getUuid()][$value->getFields()->getName()] = $value->getContent();
        }

结果是array1:

array:2 [▼
  "d8ab80f4f6" => array:16 [▶]
  9087785727 => array:16 [▶]
]

我以稍微不同的方式创建另一个数组,array2:

array:2 [▼
  "d8ab80f4f6" => array:3 [▶]
  9087785727 => array:3 [▶]
]

现在我想合并这些数组:

$output = array_merge_recursive($array1,$array2);

输出为:

array:3 [▼
  "d8ab80f4f6" => array:19 [▶]
  0 => array:3 [▶]
  1 => array:16 [▶]
]

但我希望输出为:

array:3 [▼
  "d8ab80f4f6" => array:19 [▶]
  "9087785727" => array:19 [▶]
]

您可以使用下一个 foreach loopreference &:

foreach($ar1 as $key=>&$subar){
    $subar = array_merge($subar,$ar2[$key]); 
}

Demo

array_mergearray_merge_recursive 将字符串键与数字键区别对待:

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

这就是这里发生的事情。键 9087785727 是数字,因此不会合并这些条目。

所以你需要自己写一个循环。

$output = [];
foreach ($array1 as $key => $value) {
    $output[$key] = array_merge($value, $array2[$key]);
}

DEMO