我使用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 5.6以来,原来的答案有一个更好和更干净的解决方案:
使用这样的多维数组:
$a = array(array("Mac", "NT"), array("Irix", "Linux"))
我们可以使用splat操作符:
return in_array("Irix", array_merge(...$a), true)
如果你有这样的字符串键:
$a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux"))
你将不得不使用array_values,以避免错误不能解包数组字符串键:
return in_array("Irix", array_merge(...array_values($a)), true)
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';