Sivo 悉见

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

匿名 · 更新于 2014/9/17

//判断多维数组是否存在某个值
	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; 
	}


  
我们先来解一下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法子详解页面下的评论看到的,平时没事多看看赞助手册,,特别是后面的经典评论,里面收集了不少人的经典法子啊。