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); ?>
定義和用法
array_intersect_key() 函數用於比較兩個(或更多個)數組的鍵名,並返回交集。
該函數比較兩個(或更多個)數組的鍵名,並返回交集數組,該數組包括了所有在被比較的數組(array1)中,同時也在任何其他參數數組(array2 或 array3 等等)中的鍵名。
說明
使用鍵名比較計算數組的交集。
返回一個數組,該數組包含了所有出現在被比較的數組中並同時出現在所有其他參數數組中的鍵名的值。
Comments: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); ?>
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); ?>