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

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

//print_r($a);

但是对于一个多维数组(下面)——我如何检查这个值是否存在于多数组中?

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

print_r($b);

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


当前回答

如果你的数组像这样

$array = array(
              array("name" => "Robert", "Age" => "22", "Place" => "TN"), 
              array("name" => "Henry", "Age" => "21", "Place" => "TVL")
         );

使用这个

function in_multiarray($elem, $array,$field)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom][$field] == $elem)
            return true;
        else 
            if(is_array($array[$bottom][$field]))
                if(in_multiarray($elem, ($array[$bottom][$field])))
                    return true;

        $bottom++;
    }        
    return false;
}

示例:echo in_multiarray("22", $array,"Age");

其他回答

自PHP 5.6以来,原来的答案有一个更好和更干净的解决方案:

使用这样的多维数组:

$a = array(array("Mac", "NT"), array("Irix", "Linux"))

我们可以使用splat操作符:

return in_array("Irix", array_merge(...$a), true)

如果你有这样的字符串键:

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

你将不得不使用array_values,以避免错误不能解包数组字符串键:

return in_array("Irix", array_merge(...array_values($a)), true)

这样就可以了:

foreach($b as $value)
{
    if(in_array("Irix", $value, true))
    {
        echo "Got Irix";
    }
}

In_array仅对一维数组起作用,因此需要遍历每个子数组并在每个子数组上运行In_array。

正如其他人所注意到的,这只适用于二维数组。如果有更多嵌套数组,递归版本会更好。有关例子,请参阅其他答案。

你总是可以序列化你的多维数组并执行strpos:

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

$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');

if($in_arr){
    echo "Got Irix!";
}

我使用的各种文档:

(大小写敏感) serialize () 类型杂耍或(bool)

我找到了一个非常简单的解决方法:

如果你的数组是:

Array
(
[details] => Array
    (
        [name] => Dhruv
        [salary] => 5000
    )

[score] => Array
    (
        [ssc] => 70
        [diploma] => 90
        [degree] => 70
    )

)

然后代码将像这样:

 if(in_array("5000",$array['details'])){
             echo "yes found.";
         }
     else {
             echo "no not found";
          }

那么array_search呢?根据https://gist.github.com/Ocramius/1290076的说法,似乎比foreach快得多。

if( array_search("Irix", $a) === true) 
{
    echo "Got Irix";
}