2015-04-20 60 views
0

我有什麼減去陣列讓每一個差異

$array1 = [1,1,1]; 
$array2 = [1,1]; 

我在做什麼:

array_diff($array1, $array2); 

我期待什麼:

array(1) { 1 } 

我有什麼

array(0) { } 

如何減去兩個數組以獲得每個差異?我的例子是不完整的,對不起。

如果我們也有這樣的價值觀:

$array1 = [1,1,2,1]; 
$array2 = [1,1,1,2]; 

我希望

[1,1,2,1] - [1,1,1,2] = [] 
+0

感謝@ Rizier123 – Josh

+0

您所要求的計數差U能否詳細 –

+0

'array_diff' *不*計數重複。數組1和數組2之間的唯一區別是存在第三個1。array_diff不關心這一點,並說他們是一樣的。我需要一個array_diff來做這件事:'[1,1,1] - [1,1] = [1]'。 – Josh

回答

2

array_diff_assoc()是去這裏的正道。但是爲了得到預期的結果,你只需要首先用usort()對數組進行排序,其中我將這些值與strcasecmp()進行比較。

所以這應該爲你工作:

<?php 

    $array1 = [1,1,2,1]; 
    $array2 = [1,1,1,2]; 

    function caseCmpSort($a, $b){ 
     return strcasecmp($a, $b); 
    } 

    usort($array1, "caseCmpSort"); 
    usort($array2, "caseCmpSort"); 

    $result = array_diff_assoc($array1, $array2); 

    print_r($result); 

?> 

輸出:

Array () 
+0

英雄。謝謝。 – Josh

+0

@ Jaw.sh不客氣! – Rizier123

0

manual

Returns an array containing all the entries from array1 that are not present in any of the other arrays. 

所以,它是按預期工作。我不確定你想要達到什麼目的。你雲試試吧,它應該給你預期的結果在這個的例子。

$a = [1,1,1]; 
$b = [1,1]; 
print_r(array_diff_assoc($a,$b)); 

編輯:嗯,簡單的排序應該從你的意見解決問題。不,這將刪除元素的原始索引的信息。

$a = [1,1,2,1]; 
$b = [1,1,1,2,1]; 
sort($a); 
sort($b); 
print_r(array_diff_assoc($a,$b)); 
+0

我也希望'[1,1,2,1] - [1,1,1,2] = []'。這樣做的結果是'[3 => 2,4 => 1]'。 – Josh

1

和array_diff_assoc使用

$array1 = [1,1,1]; 
$array2 = [1,1]; 
print_r(array_diff_assoc($array1, $array2)); // outputs Array ([2] => 1) 

這裏試試http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb

+0

我也期待'[1,1,2,1] - [1,1,1,2] = []'。這樣做的結果是'[3 => 2,4 => 1]'。 – Josh

+0

糾正一個小的更正[2 => 2,3 => 1] !!檢查http://sandbox.onlinephpfunctions.com/code/c8cf3134ff63a475f1376927ef71636c46370fc7 –

-1
<?php 
$n = array(1,1,1); 

$m = array(1,1); 

$r = array_diff_assoc($n,$m); 
var_dump($r); 
?>