我使用 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()
?
最佳答案
in_array()
不适用于多维数组。您可以编写一个递归函数来为您执行此操作:
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;
}
用法:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
关于php - in_array() 和多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4128323/