PHP开发过程中,经常会对数组做出处理,在这里对数组的合并,交集,差集做了整理。
首先是数组合并,关于array_merge和使用‘+’运算,可以参考之前的一篇文章。
https://blog.csdn.net/teng_liang/article/details/111937963
数组取交集 array_intersect()
第一个数组是主值,返回有相同元素的值(判断依据是元素字符串相同,即 (string) $elem1 === (string) $elem2),键值保留第一个元素的键值
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
结果
Array ( [a] => green [0] => red )
array_intersect_assoc()
array_intersect_assoc不仅检查元素值,还会检查键名,都相同的元素才会保留下来,键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red", 100 => 'a100');
$array2 = array("a" => "green", "b" => "yellow", "blue", "red", '100' => 'a100');
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
结果
Array ( [a] => green [100] => a100 )
差集 array_diff()
返回前面数组有而后面没有的元素数组,保留前面元素的键名,相同判断是根据字符串值相同,即 (string) $elem1 === (string) $elem2
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
结果
Array ( [1] => blue )
array_diff_assoc()
array_diff_assoc不仅检查元素,还检查键名,键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
结果
Array ( [b] => brown [c] => blue [0] => red )
在来个例子
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
结果
Array ( [0] => 0 [1] => 1 )
|