如果不从第二个数组创建新值,我找不到array_replace_recursive
所做的函数。
基本上我有这个数组的空值用于构造目的。然后我想从$_POST
复制具有相同键的数据。但是我不希望外键的值被复制。
$array = array(
'one' => '',
'two' => array(
'this' => '',
'that' => '',
),
// ...
);
$_POST = array(
'one' => 'a',
'two' => array(
'this' => 'b',
'that' => 'c',
'dontcopyme' => '...',
),
'dontcopyme' => 'x',
// ...
);
//$new_array = array_merge_recursive($array, $_POST);
//$new_array = array_replace_reursive($array, $_POST);
$new_array = array_dosomemagic($array, $_POST);
在这个示例中我要的结果:
array(
'one' => 'a'
'two' => array(
'this' => 'b'
'that' => 'c'
)
)
print_r($new_array);
注意:多维数组
对不起,这不是一个漂亮的一行代码,但是递归很难塞进一行。
我的方法包括一些重要的isset()
检查,以确保数组元素在尝试访问它们之前存在。你不应该在我的函数中看到任何警告/通知。
代码(演示):
function recursivePopulate($defaults,$post){
foreach($defaults as $key=>&$elem){ // make $elem modifiable by reference
if(!is_array($elem) && isset($post[$key])){ // if not an array and matching element in $_POST
$elem=$post[$key]; // store $post
}elseif(isset($post[$key])){ // only recurse subarray if exists in BOTH arrays
$elem=recursivePopulate($elem,$post[$key]); // recurse using subarray
}
}
return $defaults;
}
$defaults=[
'one'=>'one',
'two'=>[
'this'=>'this',
'that'=>'that',
['deep'=>'no match']
]
];
$_POST=[
'one'=>'New One',
'two'=>[
'this'=>'New This',
'that'=>'New That',
'dontcopyme'=>'...'
],
'dontcopyme' => 'X'
];
var_export(recursivePopulate($defaults,$_POST));
输出:array (
'one' => 'New One',
'two' =>
array (
'this' => 'New This',
'that' => 'New That',
0 =>
array (
'deep' => 'no match',
),
),
)
您可能需要array_intersect_key()
<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_intersect_key($array1, $array2));
array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
?>