1

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

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

我一直在查看文档,但目前还找不到任何东西,但在我看来,这并不是一件特别不正常的事情,因此提出了这个问题。

4

3 回答 3

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);
于 2012-09-18T11:34:59.543 回答
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));
于 2012-09-18T11:38:05.423 回答
0

I have tried following code:

// 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 )
于 2012-09-18T11:53:37.503 回答