in_array() 和多维数组 [英] in_array() and multidimensional array

查看:22
本文介绍了in_array() 和多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 in_array() 来检查一个值是否存在于如下数组中,

I use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a)) 
{
    echo "Got Irix";
}

//print_r($a);

但是多维数组呢(下面) - 我如何检查该值是否存在于多数组中?

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

或者我不应该在涉及多维数组时使用 in_array()?

or I shouldn't be using in_array() when comes to the multidimensional array?

推荐答案

in_array() 不适用于多维数组.您可以编写一个递归函数来为您做到这一点:

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

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;
}

用法:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

这篇关于in_array() 和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆