阵列相交于数组的键? [英] Array intersect on key in array?

查看:108
本文介绍了阵列相交于数组的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了国家的数组:

 阵列(
'AF'=>'阿富汗,
'AL'=>阿尔巴尼亚,
'DZ'=>'阿尔及利亚,
'为'=>美国萨摩亚,
);

和我有了一些键在它的另一个阵列

 阵列('基地','DZ');

我要打电话,将采取两个数组作为参数和返回功能

 阵列(
'AL'=>阿尔巴尼亚,
'DZ'=>'阿尔及利亚,
);

我知道PHP内置函数比较键或价值观,但似乎这些功能都期望你有两个一维数组两个二维数组。

我可以在 array_keys()循环为第一阵列,​​并做了 in_array()上的每个按键检查,但似乎真的inefficent ...


解决方案

  $选择=阵列('基地','DZ');
$ =过滤array_intersect_key($国家,array_flip($选择));
后续代码var_dump($过滤);

I have an array that has countries:

array(
'AF'=>'AFGHANISTAN',
'AL'=>'ALBANIA',
'DZ'=>'ALGERIA',
'AS'=>'AMERICAN SAMOA',
);

and I have another array that has some of the keys in it

array('AL', 'DZ');

I want to call a function that will take both arrays as parameters and return

array(
'AL'=>'ALBANIA',
'DZ'=>'ALGERIA',
);

I know php has built in functions to compare the keys, or the values, but it seems those functions all expect you to have two 1D arrays' or two 2D arrays.

I could loop over array_keys() for the first array and do a in_array() check on each key, but that seems really inefficent...

解决方案

$selection = array('AL', 'DZ');
$filtered = array_intersect_key($countries, array_flip($selection));
var_dump($filtered);

这篇关于阵列相交于数组的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆