检查多维数组中是否存在数组值

时间:2014-09-16 10:52:37

标签: php arrays multidimensional-array

我读了这篇question并回答了我的部分问题,但无论我做什么修改功能,我都没有得到预期的结果。

我想将一个数组传递给这个函数,并检查这个数组的值是否存在于多维数组中。如果$needlearray

,如何修改此功能?
//example data
$needle = array(
    [0] => someemail@example.com,
    [1] => anotheremail@example.com,
    [2] => foo@bar.com
)

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

修改

在阅读了TiMESPLiNTER提供的答案后,我按照以下方式更新了我的功能,它完美无缺。

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (is_array($needle) && is_array($item)) {
            if(array_intersect($needle,$item)) {
                return true;
            }
        }
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

1 个答案:

答案 0 :(得分:1)

检查array_intersect()是否返回至少包含一个元素的数组。如果是,$needle数组中的某个值包含在$haystack数组中。

我最终得到了这个功能:

function in_array_r($needle, $haystack) {
    $flatArray = array();

    array_walk_recursive($haystack, function($val, $key) use (&$flatArray) {
        $flatArray[] = $val;
    });

    return (count(array_intersect($needle, $flatArray)) > 0);
}

您可以扩展此功能以接受$needle$haystack的多维数组。