我使用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()当涉及到多维数组?


当前回答

这样就可以了:

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

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

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

其他回答

我相信你现在可以使用array_key_exists:

<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

伟大的功能,但它不为我工作,直到我添加了if($found){打破;}到elseif

function in_array_r($needle, $haystack) {
    $found = false;
    foreach ($haystack as $item) {
    if ($item === $needle) { 
            $found = true; 
            break; 
        } elseif (is_array($item)) {
            $found = in_array_r($needle, $item); 
            if($found) { 
                break; 
            } 
        }    
    }
    return $found;
}

自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)

如果你的数组像这样

$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");

更短的版本,用于基于数据库结果集创建的多维数组。

function in_array_r($array, $field, $find){
    foreach($array as $item){
        if($item[$field] == $find) return true;
    }
    return false;
}

$is_found = in_array_r($os_list, 'os_version', 'XP');

如果$os_list数组在os_version字段中包含'XP'则返回。