Home >php教程 >php手册 >PHP数组的交集array_intersect(),array_inter_key()等函数的小问题

PHP数组的交集array_intersect(),array_inter_key()等函数的小问题

WBOY
WBOYOriginal
2016-06-13 10:42:31942browse

求两个数组的交集问题可以使用array_intersect(),array_inersect_assoc,array_intersect_key来实现,其中array_intersect()函数是求两个数的交集,返回一个交集共有元素的数组(只是数组值得比较)、array_intersect_assoc()函数是将键值和值绑定,一起比较交集部分、array_intersect_key()函数是将两个数组的键值进行比较,返回键值交集的数组。

  但实际应用中也遇到了一些小问题,正如下:

  实例:


    "Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158);        $array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158);        $num = array_intersect($array,$array1);        print_r ($num);        echo "
";        $num = array_intersect_assoc($array,$array1);        print_r($num);        echo "
";        $num = array_intersect_key($array,$array1);        print_r ($num);    ?>
  运行结果:


Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [azzzz1] => art [peak] => 158 ) Array ( [Red15] => Red [7] => Level [Width] => Red [peak] => 158 ) Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [peak] => 158 )
  总结:

    1.array_intersect()函数进行的比较只有数组值的比较,而且存在如”Red“和”Red2“比较时会返回"Red",反之则不会返回"Red2";

    2.array_intersect_assoc()函数是将数组的值与键值一起比较,而且不会存在array_intersect的情况,适用于较严格的比较;

    3.array_intersect_key()函数适用于比较两个数组键值的交集,返回的并不只有键值,而是键值和对应的数组值。

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP+TEXT留言本(四)Next article:PHP+TEXT留言本(五)