2023-11-13 分类: 网站建设
来源:www.cnblogs.com/whyly/p/13563634.html
字符串键名相同,后面覆盖前面,数字键名会在后面追加,不覆盖,参考代码如下
$array1 = array("color" => "red", 2, 4);$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);$result = array_merge($array1, $array2);print_r($result);
结果
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
如果键名都是数字的话,后面的数组元素会追加到前面数组之后,并重建索引
$array1 = array(1 => 2, 2 => 4, 3 => 6);$array2 = array(1 => 1, 2 => 3, 3 => 5);$result = array_merge($array1, $array2);print_r($result);
结果
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 1 [4] => 3 [5] => 5 )
使用+运算符
使用+运算符合并数组,会保留前面数组的键名,后面数组元素会追加到前面数组后面,并且键名相同时,是前面覆盖后面。
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$result = $array1 + $array2;print_r($result);
结果
Array ( [0] => zero_a [2] => two_a [3] => three_a [1] => one_b [4] => four_b )
2.交集
第一个数组是主值,返回有相同元素的值(判断依据是元素字符串相同,即 (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 )
3.差集
返回前面数组有而后面没有的元素数组,保留前面元素的键名,相同判断是根据字符串值相同,即 (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 )
简单分享快乐学习,如有错误请多包涵!
pS:如果没有你的关注,那我所做的将毫无意义!欢迎分享,点赞,在看。
网站名称:创新互联pHp数组并集交集差集
链接URL:/news41/294341.html
成都网站建设公司_创新互联,为您提供网站维护、云服务器、移动网站建设、企业网站制作、网页设计公司、做网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联
猜你还喜欢下面的内容