用具有相同键的不同数组值替换内部数组值的PHP数组方法

用具有相同键的不同数组值替换内部数组值的PHP数组方法,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我试图理解PHP数组方法,所以我更喜欢使用数组方法来解决这个问题 以下是我的数据: $dataA => array 0 => array 'type' => string 'name' (length=4) 'key' => string 'keywords' (length=8) 'content' => string 'keywordA' (length=14)

我试图理解PHP数组方法,所以我更喜欢使用数组方法来解决这个问题

以下是我的数据:

$dataA =>
    array
      0 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordA' (length=14)

$dataB =>
    array
      1 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordB' (length=14)
我想做的是合并两个数组,最后的
content
键是:

$finalData =>
    array
      0 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordB' (length=14)
                               ^-- notice here that the content has changed based on the fact that 'key' for both is 'keywords'

如您所见,最终的内容值来自$dataB。

复制
$dataB
,然后循环
$dataA
。如果在
$dataB
中找不到
$dataA
的值,请将其添加到您的副本中。

递归替换会执行您想要的操作

$finalData = array_replace_recursive($dataA, $dataB);
对于此特定示例,ALLOW plus运算符将执行您想要的操作:

$finalData = $dataB + $dataA;
但您必须以不同的顺序指定参数

没有这样的内置功能。您只需要替换一个特定的键,只有当另一个键相等时,它才在第二个数组中相等,而且在零索引的数组中有关联数组,您只需要在第二个级别比较项。如果您在描述之后查看它,您可能会注意到它不是每个人都需要的通用功能,因此它不包括在标准函数集中

假设
值在每个数组中是唯一的,下面是没有可见循环的解决方案:

$getKey = function($item){ return $item['key']; };
$keysA = array_map($getKey, $dataA);
$keysB = array_map($getKey, $dataB);
$finalData = array_values(array_replace_recursive(
    array_combine($keysA, $dataA), 
    array_combine($keysB, $dataB) 
));

我尝试了array\u replace\u recursive,它只是将这两个数组组合成一个包含两个数组值的数组。索引不一样,所以它将它们组合起来。我需要寻找匹配的键索引(实际的键称为键,在本例中是关键字),然后更新值内容,因为它不同,但在本例中索引是相同的,所以我完全不理解您试图实现什么。数组a或b是否包含具有相同
键的多个元素?你需要在任何地方保留数字索引吗?现在看看。我投票结束了这个问题,就在之前,因为它的措辞不正确,所以如果是这样的话,我很抱歉。这个编辑没有回答我的任何问题。我提供的解决方案假定键值唯一,不需要数字索引。