PHP获得数组的交集与差集[转载]

原文地址:http://www.nowamagic.net/librarys/posts/php/70

数组的交集 array_intersect()

  • array_intersect()函数返回一个保留了键的数组,这个数组只由第一个数组中出现的且在其他每个输入数组中都出现的值组成。其形式如下:
array array_intersect(array array1,array array2[,arrayN…])
  • 下面这个例子将返回在fruit1数组中出现的且在fruit2和$fruit3中也出现的所有的水果:
    代码截图
<?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 )
?>
  • 只有在两个元素相等且具有相同的数据类型时,array_intersect()函数才会认为它们是相同的。

  • 函数array_intersect_assoc()与array_intersect()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。

  • 形式如下:

    array array_intersect_assoc(array array1,array array2[,arrayN…])
  • 下面的例子返回了出现在fruit1数组中,也同时出现在fruit2与$fruit3中的所有键/值对:
    代码截图
<?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 )
?>

数组的差集 array_diff()

  • 函数array_diff()返回出现在第一个数组中但其他输入数组中没有的值。这个功能与array_intersect()相反。
array array_diff(array array1,array array2[,arrayN…])

实例如下:


代码截图
<?php
    $fruit1 = array("Apple","Banana","Orange");
    $fruit2 = array("Pear","Apple","Grape");
    $fruit3 = array("Watermelon","Orange","Apple");
    $intersection = array_diff($fruit1, $fruit2, $fruit3);
    print_r($intersection); 
    // output
    // Array ( [1] => Banana )
?>

关联数组的差集 array_diff_assoc()

  • 函数array_diff_assoc()与array_diff()基本相同,只是它在比较时还考虑了数组的键。因此,只在第一个数组中出现而不再其他输入数组中出现的键/值对才会返回到结果数组中。其形式如下:
array array_diff_assoc(array array1,array array2[,arrayN…])
  • 下面的例子只返回了[yellow] => Banana,因为这个特殊的键/值对出现在fruit1中,而在fruit2和$fruit3中都不存在。
    代码截图
<?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_diff_assoc($fruit1, $fruit2, $fruit3);
    print_r($intersection); 
    // output
    // Array ( [yellow] => Banana )
?>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 总结了一些开发中常用的函数: usleep() //函数延迟代码执行若干微秒。 unpack() //函数从二进制...
    ADL2022阅读 3,308评论 0 3
  • PHP常用函数大全 usleep() 函数延迟代码执行若干微秒。 unpack() 函数从二进制字符串对数据进行解...
    上街买菜丶迷倒老太阅读 5,189评论 0 20
  • php usleep() 函数延迟代码执行若干微秒。 unpack() 函数从二进制字符串对数据进行解包。 uni...
    思梦PHP阅读 6,123评论 1 24
  • 一、Array_key_exists();检查给定的键名或索引是否存在于数组中二、array_keys ()返回数...
    peng_js阅读 2,713评论 0 0
  • 2017年8月19日,将房东遗留下来的小乌龟带到罗马湖放生了。 经历了以往认为只会出现在书上或者画面中的情节:放入...
    hailang_737d阅读 3,395评论 0 0