php in_array() 和多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4128323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:04:01  来源:igfitidea点击:

in_array() and multidimensional array

phparraysmultidimensional-array

提问by laukok

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

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

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

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

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

回答by jwueller

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

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

Usage:

用法:

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

回答by ethmz

If you know which column to search against, you can use array_search() and array_column():

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

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

This idea is in the comments section for array_search() on the PHP manual;

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

回答by NassimPHP

This will work too.

这也会起作用。

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

Usage:

用法:

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

回答by Alan Geleynse

This will do it:

这将做到:

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

in_arrayonly operates on a one dimensional array, so you need to loop over each sub array and run in_arrayon each.

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

As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.

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

回答by rynhe

if your array like this

如果你的数组是这样的

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

Use this

用这个

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

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

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

回答by Mukesh Goyal

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

回答by Fernando

Great function, but it didnt work for me until i added the if($found) { break; }to the elseif

很棒的功能,但是直到我将它添加if($found) { break; }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;
}

回答by Mohd Abdul Mujib

For Multidimensional Children:in_array('needle', array_column($arr, 'key'))

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

For One Dimensional Children:in_array('needle', call_user_func_array('array_merge', $arr))

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

回答by Mohd Abdul Mujib

You could always serialize your multi-dimensional array and do a strpos:

您始终可以序列化多维数组并执行以下操作strpos

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

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

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

Various docs for things I used:

我使用过的东西的各种文档:

回答by Fabien Salles

Since PHP 5.6there is a better and cleanersolution for the original answer :

PHP 5.6 开始,原始答案有一个更好、更清晰的解决方案:

With a multidimensional array like this :

使用这样的多维数组:

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

We can use the splat operator:

我们可以使用splat 运算符

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


If you have string keys like this :

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

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

You will have to use array_valuesin order to avoid the error Cannot unpack array with string keys:

您将不得不使用array_values以避免错误Cannot unpack array with string keys

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