我使用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()当涉及到多维数组?
我发现下面的解决方案不是很干净的代码,但它的工作。它被用作递归函数。
function in_array_multi( $needle, $array, $strict = false ) {
foreach( $array as $value ) { // Loop thorugh all values
// Check if value is aswell an array
if( is_array( $value )) {
// Recursive use of this function
if(in_array_multi( $needle, $value )) {
return true; // Break loop and return true
}
} else {
// Check if value is equal to needle
if( $strict === true ) {
if(strtolower($value) === strtolower($needle)) {
return true; // Break loop and return true
}
}else {
if(strtolower($value) == strtolower($needle)) {
return true; // Break loop and return true
}
}
}
}
return false; // Nothing found, false
}
以下是我基于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);
}
希望能有所帮助。
如果你的数组像这样
$array = array(
array("name" => "Robert", "Age" => "22", "Place" => "TN"),
array("name" => "Henry", "Age" => "21", "Place" => "TVL")
);
使用这个
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
示例:echo in_multiarray("22", $array,"Age");
我正在寻找一个函数,它可以让我在数组(干草堆)中搜索字符串和数组(如针),所以我通过@jwueller添加到答案中。
这是我的代码:
/**
* Recursive in_array function
* Searches recursively for needle in an array (haystack).
* Works with both strings and arrays as needle.
* Both needle's and haystack's keys are ignored, only values are compared.
* Note: if needle is an array, all values in needle have to be found for it to
* return true. If one value is not found, false is returned.
* @param mixed $needle The array or string to be found
* @param array $haystack The array to be searched in
* @param boolean $strict Use strict value & type validation (===) or just value
* @return boolean True if in array, false if not.
*/
function in_array_r($needle, $haystack, $strict = false) {
// array wrapper
if (is_array($needle)) {
foreach ($needle as $value) {
if (in_array_r($value, $haystack, $strict) == false) {
// an array value was not found, stop search, return false
return false;
}
}
// if the code reaches this point, all values in array have been found
return true;
}
// string handling
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle)
|| (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}