2010-08-24 36 views
1

我有兩個數組:想要得到不在數組A中的新數組?

$A = array('a','b','c','d') 
$c = array('b','c','e','f') 

我想不包含在陣列$A項目的新數組。因此,這將是:

$result = array('e','f'); 

因爲'e''f'不是$A

回答

9

使用array_diff
print_r(array_diff($c, $A));回報

Array 
(
    [2] => e 
    [3] => f 
) 
2

使用array_diff這項任務。有點討厭它不會返回兩個數組之間的所有差異。只有第一個數組中傳入的元素在任何其他數組中找不到,這些數組作爲參數傳遞。

$array1 = array('a','b','c','d'); 
$array2 = array('b','c','e','f'); 
$result = array_diff($array2, $array1); 
1

Pseduo代碼總的執行

免責聲明:不熟悉PHP,其他的答案表明有這樣做的快了很多方法,通過你的第一個數組:)

循環:

// Array of results 
array results[]; 

// Loop through all chars in first array 
for i = 0; i < A.size; i++ 
{ 
    // Have we found it in second array yet? 
    bool matched = false; 

    // Loop each character in 2nd array 
    for j = 0; j < C.size; j++ 
    { 
     // If they match, exit the loop 
     if A[i] == C[J] then 
      matched = true; 
      exit for; 
    } 

    // If we have a match add it to results 
    if matches == true then results.add(A[i]) 

}