我使用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()当涉及到多维数组?
如果你知道要搜索哪一列,你可以使用array_search()和array_column():
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
这个想法在PHP手册中array_search()的评论部分;
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';
以下是我基于json_encode()解决方案的主张:
不区分大小写选项
返回计数而不是true
数组中的任何位置(键和值)
如果没有找到word,它仍然返回0 = false。
function in_array_count($needle, $haystack, $caseSensitive = true) {
if(!$caseSensitive) {
return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
}
return substr_count(json_encode($haystack), $needle);
}
希望能有所帮助。
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;
}
自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)