PHP获得数组的交集与差集
数组的交集 array_intersect()
array_intersect()函数返回一个保留了键的数组,这个数组只由第一个数组中出现的且在其他每个输入数组中都出现的值组成。其形式如下:
[code]array array_intersect(array array1,array array2[,arrayN…])[/code]
下面这个例子将返回在$fruit1数组中出现的且在$fruit2和$fruit3中也出现的所有的水果:
[code] <?php
$fruit1 = array("Apple","Banana","Orange");
$fruit2 = array("Pear","Apple","Grape");
$fruit3 = array("Watermelon","Orange","Apple");
$intersection = array_intersect($fruit1, $fruit2, $fruit3);
print_r($intersection);
// output
// Array ( [0] => Apple )
?>[/code]
只有在两个元素相等且具有相同的数据类型时,array_intersect()函数才会认为它们是相同的。
关联数组的交集 array_intersect_assoc()
函数array_intersect_assoc()与array_intersect()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。
形式如下:
[code]array array_intersect_assoc(array array1,array array2[,arrayN…])[/code]
下面的例子返回了出现在$fruit1数组中,也同时出现在$fruit2与$fruit3中的所有键/值对:
[code] <?php
$fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
$intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3);
print_r($intersection);
// output
// Array ( [red] => Apple )
?>[/code] 濠电偞鍨堕幐鎼佀囬柆宥呮槬鐎广儱顦粈鍌炴倵閿濆骸浜濋柣鎺戞健閺屻劌鈽夐搹顐㈩伓闂備胶枪缁绘劙鎮ч幘姹団偓鍌烆敃閿曗偓缁€鍡涙煥閻曞倹瀚�闂備焦瀵х粙鎴﹀嫉椤掑倻鐜婚柟閭﹀枓閸嬫挾鎲撮崟顓犵暤闂侀潧娲らˇ鐢稿箖椤曗偓椤㈡洟顢楅崒婊庢Х濠电偛鐡ㄧ划鐘诲礂濞戞氨绠旈柕蹇嬪€曢悿顕€鏌涢埄鍐炬畼闁告ɑ妫冮弻銊モ槈濡粯鎷遍柣搴㈡皑閸嬫挸顕ラ崟顐僵妞ゆ帒顦伴埢鍏肩箾閹寸偞灏ㄩ柛瀣尵缁辨捇宕橀埡浣轰桓婵犫拃宥咁洭濞存粍鎮傞弫鎾绘晸閿燂拷