zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    160309_Qt Essentials
    160309_Qt Reference Documentation
    160308_Signals & Slots
    160308_Helloworld_Gui Application
    网络爬虫(14)-动态页面爬取
    数据分析(6)-Pandas日期数据处理
    mysql基础(2)-excel功能在excel中如何实现?
    数据分析(5)-数据可视化常用图表类型和使用场景
    财经数据(6)-Python多进程爬虫东方财富个股盘口异动数据
    财经数据(5)-开盘啦股票标签数据爬虫
  • 原文地址:https://www.cnblogs.com/clubs/p/12317919.html
Copyright © 2011-2022 走看看