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


当前回答

我发现下面的解决方案不是很干净的代码,但它的工作。它被用作递归函数。

function in_array_multi( $needle, $array, $strict = false ) {
  foreach( $array as $value ) { // Loop thorugh all values
    // Check if value is aswell an array
    if( is_array( $value )) {
      // Recursive use of this function
      if(in_array_multi( $needle, $value )) {
        return true; // Break loop and return true
      }
    } else {
      // Check if value is equal to needle
      if( $strict === true ) {
        if(strtolower($value) === strtolower($needle)) {
          return true; // Break loop and return true
        }
      }else {
        if(strtolower($value) == strtolower($needle)) {
          return true; // Break loop and return true
        }
      }
    }
  }

  return false; // Nothing found, false
}

其他回答

这个也可以。

function in_array_r($item , $array){
    return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}

用法:

if(in_array_r($item , $array)){
    // found!
}

我使用的这种方法适用于任意数量的嵌套,不需要黑客

<?php
    $blogCategories = [
        'programing' => [
            'golang',
            'php',
            'ruby',
            'functional' => [
                'Erlang',
                'Haskell'
            ]
        ],
        'bd' => [
            'mysql',
            'sqlite'
        ]
    ];
    $it = new RecursiveArrayIterator($blogCategories);
    foreach (new RecursiveIteratorIterator($it) as $t) {
        $found = $t == 'Haskell';
        if ($found) {
           break;
        }
    }

In_array()在多维数组上不起作用。你可以写一个递归函数来做这件事:

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

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

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

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'则返回。