2016-12-29 52 views
0

我如何比較兩個數組在php中?我應該如何比較兩個數組?

$arr1[0] = ['user_id' => 1, 'username' => 'bob']; 
    $arr1[1] = ['user_id' => 2, 'username' => 'tom']; 
    //and 
    $arr2[0] = ['user_id' => 2, 'username' => 'tom']; 
    $arr2[1] = ['user_id' => 3, 'username' => 'john']; 
    $arr2[2] = ['user_id' => 21, 'username' => 'taisha']; 
    $arr2[3] = ['user_id' => 1, 'username' => 'bob']; 

我需要返回不含加倍數組:

$result[0] = ['user_id' => 3, 'username' => 'john']; 
$result[1] = ['user_id' => 21, 'username' => 'taisha']; 
+0

你需要編寫一個函數來完成它。沒有簡單的預先寫好的方法。 – ChrisG

回答

2

我只想做嵌套的foreach循環

$tmpArray = array(); 

foreach($newData as $arr2) { 

    $duplicate = false; 
    foreach($oldData as $arr1) { 
    if($arr1['user_id'] === $arr2['user_id'] && $arr1['username'] === $arr2['username']) $duplicate = true; 
    } 

    if($duplicate === false) $tmpArray[] = $arr2; 
} 

然後你可以使用$ tmpArray作爲newArray

0

我爲你的問題做了一個功能

function compareArrays($array1,$array2) 
{ 
    $merged_array = array_merge($array1,$array2); 
    $trimmed_array=[]; 
    foreach($merged_array as $array) 
    { 
     $found=false; 
     $index_flag; 
     foreach($trimmed_array as $key=>$tarr) 
     { 
      if($tarr['user_id']==$array['user_id'] && $tarr['username']==$array['username']) 
      { 
       $found=true; 
       $index_flag=$key; 
       break; 
      } 
     } 
     if($found) 
     { 
      array_splice($trimmed_array, $index_flag,1); 
     } 
     else 
     { 
      array_push($trimmed_array,$array); 
     } 
    } 
    return $trimmed_array; 
} 

我測試,並得到準確的結果你的,你可以用數組調用它喜歡 -

compareArrays($arr1,$arr2); 
+0

如果你發現這個答案是你正在尋找的請接受作爲正確的答案和upvote –

0

你可以使用標準功能來實現這一目標:

// Function that sorts element array by key and 
// kinda create string representation (needed for comparing). 
$sortByKeyAndSerialize = function (array $item) { 
    ksort($item); 

    return serialize($item); 
}; 

// Map arrays to arrays of string representation and leave only unique. 
$arr1 = array_unique(array_map($sortByKeyAndSerialize, $arr1)); 
$arr2 = array_unique(array_map($sortByKeyAndSerialize, $arr2)); 

// Merge two arrays together and count values 
// (values become keys and the number of occurances become values). 
$counts = array_count_values(array_merge($arr1, $arr2)); 

// Leave only elements with value of 1 
// (i.e. occured only once). 
$unique = array_filter($counts, function ($item) { 
    return $item === 1; 
}); 

// Grab keys and unserialize them to get initial values. 
$result = array_map('unserialize', array_keys($unique)); 

這裏是working demo

隨意包裝這個代碼在一個函數或任何。

避免在代碼中使用嵌套循環,這是一個糟糕的巫術。如果可能的話,請避免使用顯式循環(例如for,while)。