我使用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()当涉及到多维数组?
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的php手册中找到的第一个此类函数。评论区的函数并不总是最好的,但如果它不能做到这一点,你也可以在那里看看:)
<?php
function in_multiarray($elem, $array)
{
// if the $array is an array or is an object
if( is_array( $array ) || is_object( $array ) )
{
// if $elem is in $array object
if( is_object( $array ) )
{
$temp_array = get_object_vars( $array );
if( in_array( $elem, $temp_array ) )
return TRUE;
}
// if $elem is in $array return true
if( is_array( $array ) && in_array( $elem, $array ) )
return TRUE;
// if $elem isn't in $array, then check foreach element
foreach( $array as $array_element )
{
// if $array_element is an array or is an object call the in_multiarray function to this element
// if in_multiarray returns TRUE, than return is in array, else check next element
if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
{
return TRUE;
exit;
}
}
}
// if isn't in array return FALSE
return FALSE;
}
?>
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;
}