[英]get available values existing in array from a list of keys php
i have this array : 我有这个数组:
$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c',
'd' => 'value of d');
this list of items : 此项目清单:
$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');
i want to check if at least one of the keys of $items exist in $array, if so return an array with one / availableones and its/their values. 我想检查$ items的键中是否至少有一个存在于$ array中,如果是这样,则返回一个包含一个/ availableones及其值的数组。
this is what i have tried so far, but cant get it right : 这是我到目前为止尝试过的,但是无法正确完成:
if (array_key_exists('a', $array) || array_key_exists('b', $array)
|| array_key_exists('c', $array) || array_key_exists('d', $array)) {
}
any help would be appreciated. 任何帮助,将不胜感激。
thanx 谢谢
What you need is a intersection of the keys between two arrays. 您需要的是两个数组之间的键的交集。 There's a nice function called
array_intersect_key()
有一个很好的函数,叫做
array_intersect_key()
http://php.net/manual/en/function.array-intersect-key.php http://php.net/manual/zh/function.array-intersect-key.php
$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c', 'd' => 'value of d');
$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');
print_r(array_intersect_key($array, $items));
Is this what you're looking for? 这是您要找的东西吗?
function search_keys($needle, $haystack) {
$matches = array();
foreach($needle as $key => $value) {
if(array_key_exists($key, $haystack)) {
$maches[$key] = $haystack[$key];
}
}
return $matches;
}
$matches = seach_keys($items, $array);
Create a function like this: 创建一个这样的函数:
function check_keys ($items, $array){
$return = false;
foreach (array_keys($items) as $key){
if (isset($array[$key])){
$return = true;
break;
}
}
return $return;
}
Call it like this: 这样称呼它:
// returns true or false
var_dump (check_keys ($items, $array));
You probably need something like this 您可能需要这样的东西
$array = array('a' => 'value of a', 'b' => 'value of b', 'c' => 'value of c', 'd' => 'value of d');
$items = array ('a' => 'value','b'=> 'value','c'=> 'value','d'=> 'value');
foreach($items as $key=>$value){
if (array_key_exists($key,$array)){
//your code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.