php 通过键获取数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4240129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get array values by keys
提问by Ayaz Alavi
I am searching for a built in php function that takes array of keys as input and returns me corresponding values.
我正在寻找一个内置的 php 函数,它将键数组作为输入并返回相应的值。
for e.g. I have a following array
例如,我有一个以下数组
$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400);
and I need values for the keys key2and key4so I have another array("key2", "key4")
I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)
并且我需要键key2和key4 的值,所以我有另一个array("key2", "key4")
我需要一个函数,该函数将这个数组和第一个数组作为输入,并为我提供响应值。所以回应将是array(200, 400)
回答by Andrew
I think you are searching for array_intersect_key. Example:
我认为您正在寻找array_intersect_key。例子:
array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),
array_flip(array('a', 'c')));
Would return:
会返回:
array('a' => 1, 'c' => 5);
You may use array('a' => '', 'c' => '')
instead of array_flip(...)
if you want to have a little simpler code.
如果您想要更简单的代码,可以使用array('a' => '', 'c' => '')
代替array_flip(...)
。
Note the array keys are preserved. You should use array_valuesafterwards if you need a sequential array.
注意数组键被保留。如果你需要一个顺序数组,你应该在之后使用array_values。
回答by Blake
An alternative answer:
另一种答案:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
回答by Amber
foreach($input_arr as $key) {
$output_arr[] = $mapping[$key];
}
This will result in $output_arr
having the values corresponding to a list of keys in $input_arr
, based on the key->value mapping in $mapping
. If you want, you could wrap it in a function:
根据 中的键->值映射,这将导致$output_arr
具有与 中的键列表相对应的$input_arr
值$mapping
。如果你愿意,你可以把它包装在一个函数中:
function get_values_for_keys($mapping, $keys) {
foreach($keys as $key) {
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
Then you would just call it like so:
然后你就可以这样称呼它:
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$values = get_values_for_keys($a, array('a', 'c'));
// $values is now array(1, 3)