从数组返回给定键的数组

时间:2012-09-18 11:28:58

标签: php

我想知道是否有一个本机PHP函数,用于返回一个由一组给定的key =>值元素组成的数组,给定一个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'
)

我一直在浏览文档,但现在还找不到任何东西,但在我看来,这似乎不是一件特别偏离的事情,因此这个问题。

3 个答案:

答案 0 :(得分:3)

这似乎是您正在寻找的:array_intesect_key

$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_intersect_key($source_array, array_flip($array_two));
$array_three_result = array_intersect_key($source_array, array_flip($array_three));

// Show it
print_r($array_two_result);
print_r($array_three_result);

答案 1 :(得分:1)

array_intersect_key - IT使用密钥计算数组的交集以进行比较。您可以将它与array_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));

答案 2 :(得分:0)

我尝试过以下代码:

// 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 )