2015-05-29 114 views
-1

我有兩個數組存放一些數據,這些數據定義用戶是否有權訪問這篇文章。該文章將被標記爲客戶端,即ClientA,ClientB,並且在創建時用戶將被分配客戶端訪問標籤。我想比較兩個數組,如果他們至少有一個我會給他們訪問,如果沒有,那麼他們將被重定向。比較兩個數組的值

array(1) { 
    [0] "ClientA" 
} 

array(3) { 
    [0] "ClientA" 
    [1] "ClientB" 
    [2] "ClientC" 
} 

我試着使用in_array但這並返回假例如:

如下面的數組結構

//$articleClient is the array with one value and $client is the 
//array with 3 values 
if (!in_array($articleClient, $client)) { 
    dd('no access'); 
} 

有關如何比較數組以查看是否存在至少一個值的任何想法?

+0

看一看'array_intersect' – Ankh

+0

不能使用in_array檢查兩個Array()函數。請參閱in_array文檔 –

+1

['in_array()'](http://php.net/manual/en/function.in-array.php) - >針必須是字符串或整數。它不能是一個數組 – Rizier123

回答

2

使用功能array_intersect函數在PHP。例如:

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); 
$a2=array("e"=>"red","f"=>"green","g"=>"blue"); 

$result=array_intersect($a1,$a2) 

if (count($result)>=1) 
{ 
    //give access to the user 
} 

鏈接:http://www.w3schools.com/php/func_array_intersect.asp

+0

偉大的作品!將在計時器用完時接受答案 – 001221

+0

@ g_9020,謝謝:) –

1

使用array_intersect()功能

1
$result = array_intersect($array1, $array2); 

if(sizeof($result)>0) 
{ 
//match 
}else 
{ 
//no match 
} 
1

試試這個

$common = array_intersect($articleClient, $client)  
if (count($common) < 1) { 
      dd('no access'); 
     }