1

我有这个数组:

$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');

我想检查 $array 中是否存在至少一个 $items 的键,如果存在,则返回一个包含一个 / availableones 及其/它们的值的数组。

这是我到目前为止所尝试的,但无法正确:

if (array_key_exists('a', $array) || array_key_exists('b', $array)
    || array_key_exists('c', $array) || array_key_exists('d', $array)) { 
}

任何帮助,将不胜感激。

谢谢

4

4 回答 4

7

您需要的是两个数组之间键的交集。有一个很好的函数叫做array_intersect_key()

http://php.net/manual/en/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));
于 2013-08-08T17:45:00.457 回答
0

这是你要找的吗?

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);
于 2013-08-08T17:41:11.380 回答
0

创建一个这样的函数:

function check_keys ($items, $array){
    $return = false;
    foreach (array_keys($items) as $key){
        if (isset($array[$key])){
            $return = true;
            break;
       }
    }
    return $return;
}

像这样称呼它:

// returns true or false
var_dump (check_keys ($items, $array));
于 2013-08-08T17:41:55.363 回答
0

你可能需要这样的东西

$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

 }
}
于 2013-08-08T17:43:54.973 回答