想要的作品雙向按鍵的遞歸差異
你的狀態,所以給你的輸入:
$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。
請從輸入,代碼的當前輸出以及期望的輸出中做一個小例子。 – Rizier123
編輯帖子。 – gaekaete
好吧,現在我們有您當前的代碼,但也可以添加例如'Array1:[1,2,3,2],數組2:[3,2,3,1,3],電流輸出:xy,預期輸出:z'就像這樣。 – Rizier123