简体   繁体   English

如果数组是数组中的in_array()?

[英]if array is in_array() in array?

First time trying to find something in an array using an array as both a needle and a haystack. 第一次尝试使用数组作为针和大海捞针在阵列中找到某些东西。 So, example of 2 arrays: 那么,2个数组的例子:

My Dynamically formed array: 我动态形成的数组:

Array ( 
    [0] => 
    [1] => zpp 
    [2] => enroll 
) 

My Static comparison array: 我的静态比较数组:

Array ( 
    [0] => enroll 
) 

And my in_array() if statement: 我的in_array() if声明:

if (in_array($location_split, $this->_acceptable)) {
   echo 'found';
}
$location_split; // is my dynamic
$this->_acceptable // is my static

But from this found is not printed out, as I'd expect it to be? 但是从这个发现的不是打印出来的,正如我所期待的那样? What exactly am I failing on here? 我究竟在这里失败了什么?

If i'm understanding you right, you want to see whether the first array's entries are present in the second array. 如果我理解你正确,你想看看第一个数组的条目是否存在于第二个数组中。

You might look at array_intersect , which would return you an array of stuff that's present in all the arrays you pass it. 你可能会看看array_intersect ,它会返回你传递给它的所有数组中存在的一些东西。

$common = array_intersect($this->_acceptable, $location_split);
if (count($common)) {
    echo 'found';
}

If the count of that array is at least 1, then there's at least one element in common. 如果该数组的计数至少为1,那么至少有一个共同的元素。 If it's equal to your dynamic array's length, and the array's values are distinct, then they're all in there. 如果它等于你的动态数组的长度,并且数组的值是不同的,那么它们都在那里。

And, of course, the array will be able to tell you which values matched. 当然,数组将能够告诉您哪些值匹配。

Because there is no element in your array containing array('enroll') in it (only 'enroll' ). 因为数组中没有包含array('enroll')元素(只有'enroll' )。

Your best bet would be to use array_diff() , if the result is the same as the original array, no match is found. 你最好的选择是使用array_diff() ,如果结果与原始数组相同,则找不到匹配项。

You are interchanging the parameters for in_array (needle & haystack). 您正在交换in_array (needle&haystack)的参数。 It needs to be, 它需要,

 if(in_array($this->_acceptable, $location_split))
{
  echo 'found';
 }

Edit: Try using array_intersect . 编辑:尝试使用array_intersect

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM