PHP头条
热点:

php判断多维数组是否存在某个值


今天我们给大家介绍如何判断数组中存在我们要找的元素值哦,这里介绍如果是一维数据就直接in_array但多维数据复杂一点。

我们先来解一下in_array检查数组中是否存在某个值

 代码如下 复制代码

<?php
$os = array("Mac", "NT", "Irix", "Linux");

echo “(1)”;
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {//in_array() 是区分大小写的
    echo "Got mac";
}

 

$a = array('1.10', 12.4, 1.13);
echo "(2)";

if (in_array('12.4', $a, true)) {//in_array() 严格类型检查
    echo "'12.4' found with strict checkn";
}
if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict checkn";
}
 

 

$a = array(array('p', 'h'), array('p', 'r'), 'o');
echo "(3)";

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was foundn";

}

if (in_array(array('f', 'i'), $a)) {//in_array() 中用数组作为 needle
    echo "'fi' was foundn";
}
if (in_array('o', $a)) {
    echo "'o' was foundn";
}
?>

 

程序运行结果是:

(1)Got Irix

(2)1.13 found with strict check

(3)'ph' was found    'o' was found


上面都是一维数组了很简单,下面来看多维数据是否存在某个值

 代码如下 复制代码

$arr = array(
   array('a', 'b'),
   array('c', 'd')
);
 
in_array('a', $arr); // 此时返回的永远都是 false
deep_in_array('a', $arr); // 此时返回 true 值
 
function deep_in_array($value, $array) { 
    foreach($array as $item) { 
        if(!is_array($item)) { 
            if ($item == $value) {
                return true;
            } else {
                continue; 
            }
        } 
         
        if(in_array($value, $item)) {
            return true;    
        } else if(deep_in_array($value, $item)) {
            return true;    
        }
    } 
    return false; 
}

 


该方法是在php帮助手册in_array方法详解页面下的评论看到的,平时没事多看看帮助手册,特别是后面的经典评论,里面收集了不少人的经典方法啊。

www.phpzy.comtrue/php/32151.htmlTechArticlephp判断多维数组是否存在某个值 今天我们给大家介绍如何判断数组中存在我们要找的元素值哦,这里介绍如果是一维数据就直接in_array但多维数据复杂一点。 我们先来解一下in_array检查...

相关文章

PHP之友评论

今天推荐