in_array()和多维数组 [英] in_array() and multidimensional array
本文介绍了in_array()和多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用 in_array()
来检查值是否存在类似下面的数组,
I use in_array()
to check whether a value exists in an array like below,
$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
echo "Got Irix";
}
//print_r($a);
但对于一个多维数组(下) - 我怎么能检查该值是否在多阵列中是否存在
but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
print_r($b);
或者我不应该使用 in_array()
当涉及到多维数组?
推荐答案
in_array()
不多维数组。你可以写一个递归函数来为你做的:
in_array()
does not work on multidimensional arrays. You could write a recursive function to do that for you:
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';
这篇关于in_array()和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文