PHP array_intersect_key() 函数

实例

比较两个数组的键名,并返回交集:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pink");
$result=array_intersect_key($a1,$a2);
print_r($result);
?>

Run Instance

定义和用法

array_intersect_key() 函数用于比较两个(或更多个)数组的键名 ,并返回交集。

该函数比较两个(或更多个)数组的键名,并返回交集数组,该数组包括了所有在被比较的数组(array1)中,同时也在任何其他参数数组(array2array3 等等)中的键名。

说明

array_intersect_key() 函数使用键名比较计算数组的交集。

array_intersect_key() 返回一个数组,该数组包含了所有出现在被比较的数组中并同时出现在所有其它参数数组中的键名的值。

Note:Only key names are used for comparison.

Syntax

array_intersect_key(array1,array2,array3...)
Parameters Description
array1 Required. The first array to compare with other arrays.
array2 Required. The array to compare with the first array.
array3,... Optional. Other arrays to compare with the first array.

Technical Details

Return Value: Returns an intersection array that includes all the key names that are present in the compared array (array1) and also in any other parameter arrays (array2 or array3, etc.).
PHP Version: 5.1.0+

More Examples

Example 1

Compare the key names of two indexed arrays and return the intersection:

<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_intersect_key($a1,$a2);
print_r($result);
?>

Run Instance

Example 2

Compare the key names of three arrays and return the intersection:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("c"=>"yellow","d"=>"black","e"=>"brown");
$a3=array("f"=>"green","c"=>"purple","g"=>"red");
$result=array_intersect_key($a1,$a2,$a3);
print_r($result);
?>

Run Instance