如何通过接管仅值从具有相同的键作为第一个第二个数组合并两个数组? [英] How to merge two arrays by taking over only values from the second array that has the same keys as the first one?

查看:181
本文介绍了如何通过接管仅值从具有相同的键作为第一个第二个数组合并两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与对方合并两个数组:

I'd like to merge two arrays with each other:

$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');

而合并应包括 $过滤并改变所有的 $这些元素中的所有元素具有相应关键 $过滤

Whereas the merge should include all elements of $filtered and all those elements of $changed that have a corresponding key in $filtered:

$merged = array(1 => 'a', 3 => 'c*');

array_merge($过滤,$改变)将增加的 $改变了附加键 $过滤为好。因此,它并不真正适合。

array_merge($filtered, $changed) would add the additional keys of $changed into $filtered as well. So it does not really fit.

我知道,我可以使用 $键= array_intersect_key($过滤,$改变)来获取存在于两个数组这已经是一半的工作的关键。

I know that I can use $keys = array_intersect_key($filtered, $changed) to get the keys that exist in both arrays which is already half of the work.

不过,我不知道是否有可以在 $更改阵列降低与 $键数组的(本地)函数 array_intersect_key ?我知道我可以使用 array_filter 有一个回调函数,并核对 $键其中,但有可能是一些其他的纯粹本地函数来从其中可以指定键的阵列仅提取那些元素

However I'm wondering if there is any (native) function that can reduce the $changed array into an array with the $keys specified by array_intersect_key? I know I can use array_filter with a callback function and check against $keys therein, but there is probably some other purely native function to extract only those elements from an array of which the keys can be specified?

我这么问是因为本地函数往往比 array_filter 快得多有一个回调。

I'm asking because the native functions are often much faster than array_filter with a callback.

推荐答案

这应该这样做,如果我理解正确你的逻辑:

This should do it, if I'm understanding your logic correctly:

array_intersect_key($changed, $filtered) + $filtered


实施

$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
$expected = array(1 => 'a', 3 => 'c*');    
$actual = array_key_merge_deceze($filtered, $changed);

var_dump($expected, $actual);

function array_key_merge_deceze($filtered, $changed) {
    $merged = array_intersect_key($changed, $filtered) + $filtered;
    ksort($merged);
    return $merged;
}

输出:

Expected:
array(2) {
  [1]=>
  string(1) "a"
  [3]=>
  string(2) "c*"
}

Actual:
array(2) {
  [1]=>
  string(1) "a"
  [3]=>
  string(2) "c*"
}

这篇关于如何通过接管仅值从具有相同的键作为第一个第二个数组合并两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆