Php 从数组返回给定键的数组

Php 从数组返回给定键的数组,php,Php,我想知道是否有一个本机PHP函数用于返回一个数组,该数组由另一个数组中给定的key=>value元素组成,给定一个require键列表。我的意思是: // Nice information $source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine'); // Required element keys $array_two = array('a'

我想知道是否有一个本机PHP函数用于返回一个数组,该数组由另一个数组中给定的key=>value元素组成,给定一个require键列表。我的意思是:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

// Get that stuff from $source_array...
// $array_two_result = ???
// $array_three_result = ???

// Show it
print_r($array_two_result);
print_r($array_three_result);
产出:

Array(
    [a] => 'hello'
    [b] => 'goodbye'
)
Array(
    [a] => 'hello'
    [d] => 'sunshine'
)

我一直在查看文档,但到目前为止还找不到任何内容,但在我看来,这并不是一件特别离经叛道的事情,因此我提出了一个问题。

这似乎就是您要寻找的:


这似乎就是您要寻找的:


array\u intersect\u key
-它使用用于比较的键计算数组的交集。您可以将其与数组_flip一起使用

print_r(array_intersect_key($source_array, array_flip(array_two_result));
print_r(array_intersect_key($source_array, array_flip($array_three_result));

array\u intersect\u key
-它使用用于比较的键计算数组的交集。您可以将其与数组_flip一起使用

print_r(array_intersect_key($source_array, array_flip(array_two_result));
print_r(array_intersect_key($source_array, array_flip($array_three_result));

我尝试了以下代码:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

function getArrayValByKey($keys_arr, $source_array){
$arr = array();
foreach($keys_arr as $key => $val){
    if(array_key_exists($val, $source_array)){
        $arr[$val] = $source_array[$val];;
    }
}

return $arr;
}

// Get that stuff from $source_array...
$array_two_result = getArrayValByKey($array_two, $source_array);
$array_three_result = getArrayValByKey($array_three, $source_array);

// Show it
print_r($array_two_result); //Array ( [a] => hello [b] => goodbye ) 
print_r($array_three_result); //Array ( [a] => hello [d] => sunshine )

我尝试了以下代码:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

function getArrayValByKey($keys_arr, $source_array){
$arr = array();
foreach($keys_arr as $key => $val){
    if(array_key_exists($val, $source_array)){
        $arr[$val] = $source_array[$val];;
    }
}

return $arr;
}

// Get that stuff from $source_array...
$array_two_result = getArrayValByKey($array_two, $source_array);
$array_three_result = getArrayValByKey($array_three, $source_array);

// Show it
print_r($array_two_result); //Array ( [a] => hello [b] => goodbye ) 
print_r($array_three_result); //Array ( [a] => hello [d] => sunshine )