array_intersect/array_diff(php实现获取数组中相同/不相同的元素)
1、获取数组相同元素
array_intersect()该函数比较两个(或更多个)数组的键值,并返回交集数组,该数组包括了所有在被比较的数组(array1)中,同时也在任何其他参数数组(array2 或 array3 等等)中的键值。
1 <?php 2 $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); 3 $a2 = array("e" => "red", "f" => "green", "g" => "blue"); 4 5 $result = array_intersect($a1, $a2); 6 print_r($result); 7 8 //Array ( [a] => red [b] => green [c] => blue )
array_intersect_assoc() 函数用于比较两个(或更多个)数组的键名和键值,并返回交集,与 array_intersect() 函数 不同的是,本函数除了比较键值,还比较键名。返回的数组中元素的键名保持不变。
1 <?php 2 $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); 3 $a2 = array("a" => "red", "b" => "green", "c" => "blue"); 4 5 $result = array_intersect_assoc($a1, $a2); 6 print_r($result); 7 8 //Array ( [a] => red [b] => green [c] => blue )
2、获取数组中不同元素
array_diff() 函数返回两个数组的差集数组。该数组包括了所有在被比较的数组中,但是不在任何其他参数数组中的键值。在返回的数组中,键名保持不变。
1 <?php 2 $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); 3 $a2 = array("e" => "red", "f" => "green", "g" => "blue"); 4 5 $result = array_diff($a1, $a2); 6 print_r($result); 7 8 //Array ( [d] => yellow )
array_diff_assoc() 函数用于比较两个(或更多个)数组的键名和键值 ,并返回差集。
<?php $a1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"); $a2 = array("a" => "red", "b" => "green", "c" => "blue"); $result = array_diff_assoc($a1, $a2); print_r($result); //Array([d] => yellow)
链接:https://mp.weixin.qq.com/s/62Szm_1nLXQV11VeBaeBgQ