2015-05-29 149 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'); 
     }