忽略不在第一个/基数组中的键值的 PHP array_merge


PHP array_merge that ignores key values that are not in the first/base array

我想知道是否有一个函数可以合并两个或多个数组,但会忽略第一个/基本数组中未包含的任何键值。

这是一个快速示例,说明我正在使用当前结果和我正在寻找的结果。

<?php
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('b' => 3, 'c' => 4);
$result = array_merge($array1, $array2);
// current result
// $result = array('a' => 1,'b' => 3, 'c' => 4);
// what i would like
// $result = array('a' => 1,'b' => 3);
?>

请求"忽略第一个/基数组中不包含的任何键值">调用array_intersect_key()

$array1 = array('a' => 1, 'b' => 2);
$array2 = array('b' => 3, 'c' => 4);
$result = array_merge($array1, array_intersect_key($array2, $array1));

array_intersect_key($array2, $array1)比较 $array2$array1 的键,并保留与两个数组通用的键关联的值$array2

这是我刚刚写的一个简单例子:

function array_merge_custom(){
    //get all the arguments
    $arrays = func_get_args();
    //get the first argument
    $first = array_shift($arrays);
    //loop over the first argument by key and value
    foreach($first as $key=>&$value){
        //loop over remaining arrays
        foreach($arrays as $otherArray){
            //check if key from first array exists in subsequent array
            if(array_key_exists($key, $otherArray)){
                //overwrite value
                $value = $otherArray[$key];
            }
        }
    }
    //return the first array with new values
    return $first;
}

http://codepad.viper-7.com/AE9rkV

这样做的好处是它适用于任意数量的数组,而不仅仅是 2 个。

我自己也遇到过类似的问题。这是我的解决方法:

<?php $array1 = array('a' => 1, 'b' => 2);
$array2 = array('b' => 3, 'c' => 4);
$result = array_intersect_key($array2, $array1) + $array1; ?>

请记住,如果您想要具有更高优先级的第二个数组,则应遵守顺序。