根据从另一个数组键array_filter [英] array_filter based on keys from another array

查看:106
本文介绍了根据从另一个数组键array_filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

$ ARR1 =阵列('A'=> 10,'B'=→20);

$ ARR2 =阵列('A'=> 10,'B'=> 20,'C'=> 30);

我如何使用array_filter下降从 $ ARR2 元素不 $ ARR1 存在吗?就像在我的例子C......


解决方案

有是专门为此做了一个功能:的 array_intersect()


  

array_intersect - 计算数组的交集


  $ ARR2 = array_intersect($ ARR1,$ ARR2);


如果您想对键进行比较,而不是像 array_intersect()值,请使用< A HREF =htt​​p://www.php.net/manual/en/function.array-intersect-key.php> array_intersect_key():


  

array_intersect_key - 计算使用比较键数组的交集


  $ ARR2 = array_intersect_key($ ARR1,$ ARR2);


如果要比较键=&GT;值对,使用<一个href=\"http://www.php.net/manual/en/function.array-intersect-assoc.php\">array_intersect_assoc():


  

array_intersect_assoc - 计算索引检查数组的交集


  $ ARR2 = array_intersect_assoc($ ARR1,$ ARR2);

I have two arrays:

$arr1 = array('a' => 10, 'b' => 20);

$arr2 = array('a' => 10, 'b' => 20, 'c' => 30);

How can I use array_filter to drop elements from $arr2 that don't exist in $arr1 ? Like "c" in my example...

解决方案

There is a function specifically made for this purpose: array_intersect():

array_intersect — Computes the intersection of arrays

$arr2 = array_intersect($arr1, $arr2);


If you want to compare keys, not the values like array_intersect(), use array_intersect_key():

array_intersect_key — Computes the intersection of arrays using keys for comparison

$arr2 = array_intersect_key($arr1, $arr2); 


If you want to compare key=>value pairs, use array_intersect_assoc():

array_intersect_assoc — Computes the intersection of arrays with additional index check

$arr2 = array_intersect_assoc($arr1, $arr2); 

这篇关于根据从另一个数组键array_filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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