2015-05-27 52 views
0

我有两个数组:PHP Comapring数组包含相同的字符串,但不包括相同的行

$a = array (

[0] => 0 
[1] => 1 
[2] => 2 
[3] => 3 

) 

$b = array (

[0] => 2 
[1] => 1 
[2] => 3 
[3] => 4 

) 

如果我要算的是同一个对象,我可以用array_intersect - >echo count(array_intersect($a,$b));。 将返回:3

不过,我想他们排除相同的行:

$a = array (

[0] => 0 
[1] => 1 //Both are the same that I would like to exclude 
[2] => 2 
[3] => 3 

) 

$b = array (

[0] => 2 
[1] => 1 //Both are the same that I would like to exclude 
[2] => 3 
[3] => 4 

) 

这只会返回2

我该怎么做?由于

+0

我不明白。你的第一个和第二个例子有什么不同? –

+0

@JohnCartwright它是一样的,但数组'$ a'和'$ b'具有相同的行:'[1] => 1',我想从返回值中排除 –

回答

1

我会用一个循环,想不出别的现在。

$identical = 0; 
for($i = 0; $i < count($a); $i++) { 
    if(isset($b[$i]) && $a[$i] === $b[$i]) { 
     $identical++; 
    } 
} 
$count = count(array_intersect($a,$b)) - $identical; 
$count = ($count < 0) ? 0 : $count; 
echo $count; 
1

试试这个

$a = array (0,1,2,3); 
$b = array (2,1,3,4); 

$final = array_unique(array_merge($a,$b)); 

print "total : ". count($final); 
+0

对不起,我试过但它返回5? [code](http://www.jamiephan.net/MyStuff/so/test.php) –

+0

是的,这段代码结合了数组并删除重复的值,那么count的结果就是5。 – Offboard

相关问题