I would like to set an associative array of default keys and values(array1); If an array is provided (array2) then all indexes from array1 will be overwritten by array2 where the keys match. Any additional keys in array2 wont be added to array1.
我想设置一个默认键和值的关联数组(array1);如果提供了一个数组(array2),那么array1的所有索引都将被array2覆盖,其中的键匹配。array2中的任何附加键都不会被添加到array1。
One solution is to run a loop and do a array_key_exists
like so.
一种解决方案是运行一个循环并像这样执行array_key_exists。
$new_array = $array1;
foreach ($array2 as $key => $value) {
if(array_key_exists($key, $array1)){
$new_array[$key] = $value; //overwrite default value
} else {
// new key, dont add
}
}
but is there a php function which does this already ?
但是有一个php函数已经这样做了吗?
the functions i have tries already dont give my the results i would like.
我已经尝试过的功能并没有给出我想要的结果。
$array1 = array(
'one' =>'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'
);
$array2 = array(
'two' => '2',
'four' => '4',
'six' => '6',
);
var_dump($array1+$array2);
array (size=5)
'one' => string 'one' (length=3)
'two' => string 'two' (length=3)
'three' => string 'three' (length=5)
'four' => string 'four' (length=4)
'six' => string '6' (length=1)
var_dump(array_merge($array1,$array2));
array (size=5)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)
'six' => string '6' (length=1)
var_dump(array_replace($array1,$array2));
array (size=5)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)
'six' => string '6' (length=1)
The result i am looking for would be
我想要的结果是
array (size=4)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)
1 个解决方案
#1
4
Take from 2nd array keys, present in 1st, and replace value in 1st
从2个数组键中取1,替换1
print_r(array_replace($array1, array_intersect_key($array2, $array1)));
#1
4
Take from 2nd array keys, present in 1st, and replace value in 1st
从2个数组键中取1,替换1
print_r(array_replace($array1, array_intersect_key($array2, $array1)));