2010-09-04 70 views
1

厚厚的—真是對不起。 :)無論如何,我有2個數組,我想操縱;如果第一個數組中的值存在於第二個數組中,則執行一件事,然後對第二個數組的其餘值執行其他操作。php array - in_array和/或array_intersect

例如

$array1 = array('1','2','3','4'); - the needle 
$array2 = array('1','3','5','7'); - the haystack 

if(in_array($array1,$array2): echo 'the needle'; else: echo'the haystack LESS the needle '; endif; 

但由於某種原因,in_array不適用於我。請幫助。

+0

你的意思是從針「的任何值」或「所有值」必須出現在草堆? – Matthew 2010-09-04 08:17:42

回答

3

做這樣的:

<?php 
$array1 = array('1','2','3','4'); 
$array2 = array('1','3','5','7'); 

//case 1: 
print_r(array_intersect($array1, $array2)); 

//case 2: 
print_r(array_diff($array2, $array1)); 
?> 

此輸出數組(你早想問題修改前)的價值觀:

Array 
(
    [0] => 1 
    [2] => 3 
) 
Array 
(
    [2] => 5 
    [3] => 7 
) 

而且,如果你想使用if-else,這樣做:

<?php 
$array1 = array('1','2','3','4'); 
$array2 = array('1','3','5','7'); 

$intesect = array_intersect($array1, $array2); 

if(count($intesect)) 
{ 
    echo 'the needle'; 
    print_r($intesect); 
} 
else 
{ 
    echo'the haystack LESS the needle '; 
    print_r(array_diff($array2, $array1)); 
} 
?> 

此輸出:

the needle 
Array 
(
    [0] => 1 
    [2] => 3 
) 
+0

謝謝shamittomar - 說是想着,我不能得到第一個數組到array_diff,因爲我以前曾經以某種方式操作它(現在忘記了),因爲你的代碼作爲一個夢想 – user351657 2010-09-04 08:15:05

+0

如果這實際上是你想要的,那麼'array_diff'是完全多餘的,因爲你已經確定交集爲空。 – Matthew 2010-09-04 08:19:01

+0

@ konforce,是的,我同意,但在原來的問題(這是現在修改),它被要求顯示剩餘價值。 – shamittomar 2010-09-04 08:56:08