1、获取数组相同元素
array_intersect()该函数比较两个(或更多个)数组的键值,并返回交集数组,该数组包括了所有在被比较的数组(array1)中,
同时也在任何其他参数数组(array2 或 array3 等等)中的键值。
1
2
3
4
5
6
7
8
9
|
<?php $a1 = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ); $a2 = array ( "e" => "red" , "f" => "green" , "g" => "blue" ); $result = array_intersect ( $a1 , $a2 ); print_r( $result ); // Array ( [a] => red [b] => green [c] => blue ) |
array_intersect_assoc() 函数用于比较两个(或更多个)数组的键名和键值,并返回交集,与 array_intersect() 函数 不同的是,本函数除了比较键值,
还比较键名。返回的数组中元素的键名保持不变。
1
2
3
4
5
6
7
8
9
|
<?php $a1 = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ); $a2 = array ( "a" => "red" , "b" => "green" , "c" => "blue" ); $result = array_intersect_assoc ( $a1 , $a2 ); print_r( $result ); ?> // Array ( [a] => red [b] => green [c] => blue ) |
2、获取数组中不同元素
array_diff() 函数返回两个数组的差集数组。该数组包括了所有在被比较的数组中,但是不在任何其他参数数组中的键值。
在返回的数组中,键名保持不变。
1
2
3
4
5
6
7
8
9
|
<?php $a1 = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ); $a2 = array ( "e" => "red" , "f" => "green" , "g" => "blue" ); $result = array_diff ( $a1 , $a2 ); print_r( $result ); ?> // Array ( [d] => yellow ) |
array_diff_assoc() 函数用于比较两个(或更多个)数组的键名和键值 ,并返回差集。
1
2
3
4
5
6
7
8
|
<?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 ) |
以上这篇php 比较获取两个数组相同和不同元素的例子(交集和差集)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qazx123q/article/details/79634613