我使用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_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所接受的解决方案(在撰写本文时)

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在比较不同类型的值时的类型杂耍

"example" == 0

and

0 == "example"

计算值为true,因为"example"被强制转换为int并转换为0。

(参见为什么PHP认为0等于一个字符串?)

如果这不是理想的行为,在进行非严格比较之前,可以方便地将数值转换为字符串:

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

请尝试:

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

我不确定是否需要,但这个也许能满足你的要求

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

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

我正在寻找一个函数,它可以让我在数组(干草堆)中搜索字符串和数组(如针),所以我通过@jwueller添加到答案中。

这是我的代码:

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

如果你知道要搜索哪一列,你可以使用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';
}

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