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


Check if array value exists in multidimensional array

我读过这个问题,它回答了我的部分问题,但无论我如何修改函数,我都没有得到预期的结果。

我想把一个数组传递给这个函数,并检查这个数组的值是否存在于多维数组中。如果$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;
}

检查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的多维数组。