2015-08-17 64 views
2

我想在兩個多維數組上應用array_diff_key()遞歸地並找出它們之間的區別。PHP - 「雙向」遞歸array_diff_key()

,該功能將是 「雙向」 所以FOO($ A,$ B)FOO($ B $ A)將產生相同的結果是很重要的。

我試過了什麼?說實話,我嘗試了太多東西(包括http://php.net/manual/en/function.array-diff-key.php的例子)並迷路了。

function superMatch($a1, $a2) { 

    foreach($a1 as $k => $v) { 
     $r[$k] = is_array($v) ? superMatch($a1[$k], $a2[$k]) : array_diff_key($a1, $a2); 
    } 

    return $r; 
} 

輸入:

$a = array('a' => 'a', 'b' => 'b', 'c' => array('d' => 'd', 'e' => 'e')); 
$a = array('a' => 'a', 'b' => 'b', 'c' => array('t' => 'd', 'e' => 'e')); 

預計輸出: 'T'

可有人請給我一個線索?

+1

請從輸入,代碼的當前輸出以及期望的輸出中做一個小例子。 – Rizier123

+0

編輯帖子。 – gaekaete

+0

好吧,現在我們有您當前的代碼,但也可以添加例如'Array1:[1,2,3,2],數組2:[3,2,3,1,3],電流輸出:xy,預期輸出:z'就像這樣。 – Rizier123

回答

1
想要的作品雙向按鍵的遞歸差異

你的狀態,所以給你的輸入:

$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