数组 函数
PHP Manual

array_intersect_key

(PHP 5 >= 5.1.0)

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

说明

array array_intersect_key ( array $array1 , array $array2 [, array $ ... ] )

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

Example #1 array_intersect_key() 例子

<?php
$array1 
= array('blue'  => 1'red'  => 2'green'  => 3'purple' => 4);
$array2 = array('green' => 5'blue' => 6'yellow' => 7'cyan'   => 8);

var_dump(array_intersect_key($array1$array2));
?>

以上例程会输出:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

上例中可以看到只有 'blue''green' 两个键名出现在两个数组中,因此被返回。此外注意 'blue''green' 的值在两个数组中是不同的。但因为只检查键名,因此还是匹配。返回的值只是 array1 中的。

key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时被认为相等。换句话说,执行的是严格类型检查,因此字符串的表达必须完全一样。

参见 array_diff()array_udiff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_diff_key()array_diff_ukey()array_intersect()array_intersect_assoc()array_intersect_uassoc()array_intersect_ukey()

参数

array1

The array with master keys to check.

array2

An array to compare keys against.

array

A variable list of arrays to compare.

返回值

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments.

范例

Example #2 array_intersect_key() example

<?php
$array1 
= array('blue'  => 1'red'  => 2'green'  => 3'purple' => 4);
$array2 = array('green' => 5'blue' => 6'yellow' => 7'cyan'   => 8);

var_dump(array_intersect_key($array1$array2));
?>

以上例程会输出:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

参见


数组 函数
PHP Manual