关于php:in_array()和多维数组

in_array() and multidimensional array

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

1
2
3
4
5
6
7
$a = array("Mac","NT","Irix","Linux");
if (in_array("Irix", $a))
{
    echo"Got Irix";
}

//print_r($a);

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

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

print_r($b);

还是多维数组不应该使用in_array()


in_array()在多维数组上不起作用。您可以编写一个递归函数来为您做到这一点:

1
2
3
4
5
6
7
8
9
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;
}

用法:

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


这也将起作用。

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

用法:

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


如果知道要搜索的列,则可以使用array_search()和array_column():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

这个想法在PHP手册的array_search()的注释部分中。


这样做:

1
2
3
4
5
6
7
foreach($b as $value)
{
    if(in_array("Irix", $value, true))
    {
        echo"Got Irix";
    }
}

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

正如其他人指出的那样,这仅适用于二维数组。如果您有更多的嵌套数组,则使用递归版本会更好。有关示例,请参见其他答案。


如果你的数组是这样的

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

用这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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");


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));

if($url_in_array) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}


很棒的功能,但是直到我将if($found) { break; }添加到elseif之前,它对我都没有用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}

对于多维儿童:in_array('needle', array_column($arr, 'key'))

对于一维儿童:in_array('needle', call_user_func_array('array_merge', $arr))


您总是可以序列化多维数组并执行strpos

1
2
3
4
5
6
7
$arr = array(array("Mac","NT"), array("Irix","Linux"));

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

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

我使用过的各种文档:

  • strpos()
  • 连载()
  • 类型杂耍或(布尔)


从PHP 5.6开始,有一个更好,更干净的解决方案用于原始答案:

使用这样的多维数组:

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

我们可以使用splat运算符:

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

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

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

您必须使用array_values以避免错误Cannot unpack array with string keys

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

jwueller接受的解决方案(在撰写本文时)

1
2
3
4
5
6
7
8
9
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;
}

是完全正确的,但是在进行弱比较(参数$strict = false)时可能会有意外的行为。

由于PHP在比较不同类型的值时都会变类型

1
"example" == 0

1
0 =="example"

评估true,因为"example"被强制转换为int并变成了0

(请参阅为什么PHP认为0等于字符串?)

如果这不是所需的行为,则在进行非严格比较之前将数字值转换为字符串会很方便:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {

        if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
            $item = (string)$item;
        }

        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

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

1
2
3
4
5
6
7
8
9
10
11
<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo"Key exists!";
  }
else
  {
  echo"Key does not exist!";
  }
?>

这是我基于json_encode()解决方案的主张:

  • 不区分大小写的选项
  • 返回计数而不是true
  • 数组中的任何地方(键和值)

如果找不到单词,它仍然返回0等于false。

1
2
3
4
5
6
function in_array_count($needle, $haystack, $caseSensitive = true) {
    if(!$caseSensitive) {
        return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
    }
    return substr_count(json_encode($haystack), $needle);
}

希望能帮助到你。


这是我在in_array的php手册中找到的这种类型的第一个功能。注释部分中的功能并不总是最好的,但如果不能解决问题,您也可以在这里查看:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
function in_multiarray($elem, $array)
    {
        // if the $array is an array or is an object
         if( is_array( $array ) || is_object( $array ) )
         {
             // if $elem is in $array object
             if( is_object( $array ) )
             {
                 $temp_array = get_object_vars( $array );
                 if( in_array( $elem, $temp_array ) )
                     return TRUE;
             }

             // if $elem is in $array return true
             if( is_array( $array ) && in_array( $elem, $array ) )
                 return TRUE;


             // if $elem isn't in $array, then check foreach element
             foreach( $array as $array_element )
             {
                 // if $array_element is an array or is an object call the in_multiarray function to this element
                 // if in_multiarray returns TRUE, than return is in array, else check next element
                 if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
                 {
                     return TRUE;
                     exit;
                 }
             }
         }

         // if isn't in array return FALSE
         return FALSE;
    }
?>


它也可以从原始数组创建一个新的一维数组。

1
2
3
4
5
$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");

foreach ($arr as $row)  $vector[] = $row['key1'];

in_array($needle,$vector);

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

1
2
3
4
5
6
7
8
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",则将返回。


我一直在寻找一个可以让我在数组(干草堆)中搜索字符串和数组(作为指针)的函数,因此我在@jwueller的答案中添加了该函数。

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Recursive in_array function
 * Searches recursively for needle in an array (haystack).
 * Works with both strings and arrays as needle.
 * Both needle's and haystack's keys are ignored, only values are compared.
 * Note: if needle is an array, all values in needle have to be found for it to
 * return true. If one value is not found, false is returned.
 * @param  mixed   $needle   The array or string to be found
 * @param  array   $haystack The array to be searched in
 * @param  boolean $strict   Use strict value & type validation (===) or just value
 * @return boolean           True if in array, false if not.
 */

function in_array_r($needle, $haystack, $strict = false) {
     // array wrapper
    if (is_array($needle)) {
        foreach ($needle as $value) {
            if (in_array_r($value, $haystack, $strict) == false) {
                // an array value was not found, stop search, return false
                return false;
            }
        }
        // if the code reaches this point, all values in array have been found
        return true;
    }

    // string handling
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle)
            || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

我发现了非常小的简单解决方案:

如果您的数组是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Array
(
[details] => Array
    (
        [name] => Dhruv
        [salary] => 5000
    )

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

)

那么代码将是这样的:

1
2
3
4
5
6
 if(in_array("5000",$array['details'])){
             echo"yes found.";
         }
     else {
             echo"no not found";
          }

我使用此方法可用于任意数量的嵌套,不需要黑客入侵

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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;
        }
    }


请试试:

1
2
in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

我不确定需求,但这可能会满足您的要求


你可以这样使用

1
2
$result = array_intersect($array1, $array2);
print_r($result);

http://php.net/manual/tr/function.array-intersect.php


那么array_search呢?根据https://gist.github.com/Ocramius/1290076,它似乎比foreach更快。

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