Check If In_Array (in Recursive Associative Array)

我是研究僧i 提交于 2019-12-13 23:11:25

问题


I have an array similar to this:

array(2) {
  [0]=>
  array(2) {
    ["code"]=>
    string(2) "en"
    ["name"]=>
    string(7) "English"
  }
  [1]=>
  array(2) {
    ["code"]=>
    string(2) "bg"
    ["name"]=>
    string(9) "Bulgarian"
  }
}

How do I check if the string Bulgarian is part of the above array, or alternatively if the lang code 'en' is part of the array? It would be great if I didn't have to use foreach to loop through the entire array and compare the string with each element['code'] or element['name'].


回答1:


// $type could be code or name
function check_in_array($arr, $value, $type = "code") {
  return count(array_filter($arr, function($var) use ($type, $value) {
    return $var[$type] === $value;
  })) !== 0;
}



回答2:


I know my code used foreach but it is easy to understand and use.

$language=array();
$language[0]['code']='en';
$language[0]['name']='English';
$language[1]['code']='bg';
$language[1]['name']='Bulgaria';

var_dump(my_in_array('Bulgaria', $language));

function my_in_array($search, $array) {
    $in_keys = array();
    foreach($array as $key => $value){
        if(in_array($search, $value)){
            $in_keys[]=$key;
        }
    }
    if(count($in_keys) > 0){
        return $in_keys;
    }else{
        return false;
    }
}



回答3:


You can use this function for recursive search

function in_arrayr($needle, $haystack) {
        foreach ($haystack as $v) {
                if ($needle == $v) return true;
                elseif (is_array($v)) return in_array($needle, $v);
        }
        return false;
} 

Or you can use json_encode on your array and search occurence of substring :)




回答4:


I had a similar problem, so I made this function, it's like in_array, but it can search in array in the array recursively. I think it's correct but I didn't test in a lot of case. (sorry for my english I'm french)

function in_arrayr($needle, $haystack) {
if(is_array($haystack)){
    foreach($haystack as $elem){
        $a = in_arrayr($needle,$elem)||$a;
    }
}
else{
    $a = (($needle == $haystack)? true: false);
}
    return $a;
} 


来源:https://stackoverflow.com/questions/11009875/check-if-in-array-in-recursive-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!