Duke Yin's Technology database

PHP判断数组里是否有某值

in_array()

bool in_array ( $val, $array_name ,$mode )

in_array()输出布尔值真或假,作为某值是否在数组里的判断。

比如:

<?php 
$marks = array(100, 65, 70, 87); 
if ( in_array("100", $marks,true) ) 
  { 
echo "found";  
} 
else{ 
  echo "not found"; 
 } 
?> 

但是,in_array()对于有子数组的数组无能为力,如果需要查询更底层或更复杂的数组,需要构件一个自定义函数进行查询:

<?php
function in_array_recursive($needle, $haystack) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
foreach($it AS $element) {
	if($element == $needle) {
		return true;
		}
	}
	return false;
}

如此一来,我们就能使用 in_array_recursive() 代替 in_array() 进行子数组的查询,例如:

$array = Array
(
[0] => Array
    (
        [0] => 225
        [1] => 226
        [2] => 227
        [3] => 228
        [4] => 229
        [5] => 230
        [6] => 340
        [7] => 355
    )

[1] => Array
    (
        [0] => 313
        [1] => 314
        [2] => 315
        [3] => 316
        [4] => 318
        [5] => 319
    )

[2] => Array
    (
        [0] => 298
        [1] => 301
        [2] => 302
        [3] => 338
    )

)

if( in_array_recursive( 225 , $array ) ){
echo "found 225 in array";
}

引用关闭,但你能发布评论.

评论

标注 * 的为必填项。