这5个获取交集的函数 有 5个对应的获取差集的函数。我是链接。
array_intersect($arr1, $arr2);
//获得数组同键值的交集
array_intersect_key($arr1, $arr2);
//获得数组同键名的交集
array_intersect_assoc(同上);
//获得数组同键名键值的交集
array_intersect_uassoc(同上,'自定义回调函数');
//用自定义的回调函数来获得数组同键名键值的交集
array_intersect_ukey(同上, 自定义回调函数);
//用自定义的回调函数来获得数据同键名的交集
$arr1 = array('r' => 'red','u' => 'blue', 'g' => 'green', 'b' => 'black');
$arr2 = array('r' => 'red', 'b' => 'blue');
/***********array_intersect(计算数组同键值的交集)*****************/
$arrIntersect = array_intersect($arr1, $arr2);
var_dump($arrIntersect);//=>array(2) { ["r"]=> string(3) "red" ["u"]=> string(4) "blue" } /***********array_intersect_key(计算数组同键名的交集)*****************/
$arrIntersectKey = array_intersect_key($arr1, $arr2);
var_dump($arrIntersectKey);//=>array(2) { ["r"]=> string(3) "red" ["b"]=> string(5) "black" } /***********array_intersect_assoc(计算数组同键名同键值的交集)*****************/
$arrIntersectAssoc = array_intersect_assoc($arr1, $arr2);
var_dump($arrIntersectAssoc);//=>array(1) { ["r"]=> string(3) "red" } /***********array_intersect_uassoc(用自定义的回调函数来计算数组同键名同键值的交集)*****************/
$arrIntersectUassoc = array_intersect_uassoc($arr1, $arr2, 'arr_intersect_uassoc_func');
var_dump($arrIntersectUassoc);//=>array(1) { ["r"]=> string(3) "red" } function arr_intersect_uassoc_func($a, $b) {
if ($a === $b)
return 0;
elseif ($a > $b)
return 1;
else
return -1;
} /***********array_intersect_ukey(用自定义的回调函数来计算数组同键名的交集)*****************/
$arrIntersectUkey = array_intersect_ukey($arr1, $arr2, 'arr_intersect_ukey_func');
var_dump($arrIntersectUkey);//=>array(2) { ["r"]=> string(3) "red" ["b"]=> string(5) "black" } function arr_intersect_ukey_func($k1, $k2) {
if ($k1 == $k2)
return 0;
elseif ($k1 > $k2)
return 1;
else
return -1;
}