你声明你想要双向工作的键的递归差异,所以给定你的输入:
$a = array('a' => 'a', 'b' => 'b', 'c' => array('d' => 'd', 'e' => 'e'));
$b = array('a' => 'a', 'b' => 'b', 'c' => array('t' => 'd', 'e' => 'e'));
你应该得到输出:
$output = array('c'=>array('d'=>'d','t'=>'d'));
//or
$output = array('t'=>'d','d'=>'d');
以下方法将返回输出的第一个版本。但是,您在问题中说,它应该只输出 t,这没有意义,因为它不可能双向工作(因为密钥 d 也不匹配)。
/** return an array that contains keys that do not match between $array and $compare, checking recursively.
* It's bi-directional so it doesn't matter which param is first
*
* @param $array an array to compare
* @param $compare another array
*
* @return an array that contains keys that do not match between $array and $compare
*/
function keyMatch($array,$compare){
$output = array();
foreach ($array as $key=>$value){
if (!array_key_exists($key,$compare)){
//keys don't match, so add to output array
$output[$key] = $value;
} else if (is_array($value)||is_array($compare[$key])){
//there is a sub array to search, and the keys match in the parent array
$match = keyMatch($value,$compare[$key]);
if (count($match)>0){
//if $match is empty, then there wasn't actually a match to add to $output
$output[$key] = $match;
}
}
}
//Literally just renaiming $array to $compare and $compare to $array
// Why? because I copy-pasted the first foreach loop
$compareCopy = $compare;
$compare = $array;
$array = $compareCopy;
foreach ($array as $key=>$value){
if (!array_key_exists($key,$compare)){
$output[$key] = $value;
} else if (is_array($value)||is_array($compare[$key])){
$match = keyMatch($value,$compare[$key]);
if (count($match)>0){
$output[$key] = $match;
}
}
}
return $output;
}
$a = array('a' => 'a', 'b' => 'b', 'c' => array('d' => 'd', 'e' => 'e'));
$b = array('a' => 'a', 'b' => 'b', 'c' => array('t' => 'd', 'e' => 'e'));
print_r(keyMatch($a,$b));
哦,这是您的小型示例输入中的example of it working。