如何在php中使用in_array并将数组作为needle,但在至少有一个值匹配时返回true

时间:2016-07-02 06:24:16

标签: php arrays

这是我的func swipeViewDidScroll(swipeView: SwipeView!) { //USE swipeView.currentItemView to access current view //USE swipeView.itemViewAtIndex(swipeView.currentItemIndex - 1) to access previous view //USE swipeView.itemViewAtIndex(swipeView.currentItemIndex + 1) to access next View swipeView.currentItemView.frame = CGRect(x: swipeView.currentItemView.bounds.origin.x, y: swipeView.currentItemView.bounds.origin.y , width: (swipeView.currentItemView.bounds.width + swipeView.scrollOffset) - CGFloat((280 * swipeView.currentItemIndex)), height: swipeView.currentItemView.bounds.height) } 代码

in_array

它返回未找到,但实际上我希望它返回$array = array('a', 'b', 'c'); if(in_array(array('p', 'c'), $array)){ echo "found"; }else{ echo "not found"; } ,因为有一个值匹配found

3 个答案:

答案 0 :(得分:4)

您的想法可以通过使用array_intersectcount函数来实现。
如果两个数组之间至少有一个匹配的项目 - count将返回匹配项的数量(1或更多):

$needle = array('p', 'c');
$haystack = array('a', 'b', 'c');

echo (count(array_intersect($needle, $haystack))) ? "found" : "not found";
// will output: "found"

http://php.net/manual/en/function.array-intersect.php

答案 1 :(得分:2)

使用array_interset(): -

$search = array('p', 'c');
$array = array('a', 'b', 'c');

$result = !empty(array_intersect($search , $array ));

var_dump($result); // print result

//OR
if(count($result) >=1){echo 'found';}else{'not found';}

输出: - https://eval.in/599429

参考: -

http://php.net/manual/en/function.array-intersect.php

答案 2 :(得分:2)

通过创建用户功能的另一种方法

function found_in_array($needle, $haystack) {
    foreach ($needle as $array) {
        if(in_array($array, $haystack)){
            return "found";
        }
    }

    return "not found";
}

$haystack = array('a', 'b', 'c');
$needle = array('p', 'c');

echo found_in_array($needle, $haystack);