数组与数组中的键相交? [英] Array intersect on key in array?

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

问题描述

我有一个包含国家/地区的数组:

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',
);

我知道 php 有内置函数来比较键或值,但似乎这些函数都希望你有两个一维数组或两个二维数组.

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.

我可以为第一个数组循环 array_keys() 并对每个键进行 in_array() 检查,但这似乎非常低效...

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天全站免登陆