zoukankan      html  css  js  c++  java
  • array_uintersect、array_uintersect_assoc、array_uintersect_uassoc 的使用方法

     和 array_intersect 类似,只不过 array_uintersect* 系列函数的值比较使用自定义函数;

    键的比较,array_uintersect、array_uintersect_assoc 是使用内置方法, array_uintersect_uassoc 是使用自定义函数。

    <?php
    
    // array_uintersect 用自定义函数比较数组的交值(array_intersect 使用内置函数)
    // 使用该函数我们通过进行更复杂的比较
    
    class Rectangle
    {
        public $width;
    
        public $height;
    
        public function __construct($width, $height)
        {
            $this->width = $width;
            $this->height = $height;
        }
    }
    
    $array1 = [
        'a' => new Rectangle(1, 2),
        'b' => new Rectangle(2, 3),
        'c' => new Rectangle(3, 5),
    ];
    
    $array2 = [
        'a' => new Rectangle(2, 3),
        'c' => new Rectangle(3, 5),
    ];
    
    // 键比较函数
    function compare_key($key1, $key2) {
        if ($key1 == $key2) {
            return 0;
        }
    
        return $key1 > $key2 ? 1 : -1;
    }
    
    // 值比较函数
    function compare_area(Rectangle $value1, Rectangle $value2) {
        $area1 = $value1->width * $value1->height;
        $area2 = $value2->width * $value2->height;
    
        if ($area1 == $area2) {
            return 0;
        }
        return $area1 > $area2 ? 1 : -1;
    }
    
    // 返回数组交集, 只比较值 (值的比较使用自定义函数)
    var_dump(array_uintersect($array1, $array2, 'compare_area'));
    
    // 返回数组交集, 同时比较键和值(值的比较使用自定义函数, 键的比较使用内置方法)
    var_dump(array_uintersect_assoc($array1, $array2, 'compare_area'));
    
    // 返回数组交集, 同时比较键和值(值的比较使用自定义函数,键的比较使用自定义函数)
    var_dump(array_uintersect_uassoc($array1, $array2, 'compare_area', 'compare_key'));
    

      

    输出:

    array(2) {
      ["b"]=>
      object(Rectangle)#2 (2) {
        ["width"]=>
        int(2)
        ["height"]=>
        int(3)
      }
      ["c"]=>
      object(Rectangle)#3 (2) {
        ["width"]=>
        int(3)
        ["height"]=>
        int(5)
      }
    }
    array(1) {
      ["c"]=>
      object(Rectangle)#3 (2) {
        ["width"]=>
        int(3)
        ["height"]=>
        int(5)
      }
    }
    array(1) {
      ["c"]=>
      object(Rectangle)#3 (2) {
        ["width"]=>
        int(3)
        ["height"]=>
        int(5)
      }
    }
    

      

  • 相关阅读:
    /proc/uptime详解
    UE没法远程修改文件
    ssh隐藏的sftp功能的使用
    ftp配置文件
    如何判断网线是否连接
    NTP多种模式的配置
    系统开机启动过程
    window BIOS设置硬盘启动模式
    shell加密
    /etc/sysconfig/network-scripts/下文件介绍
  • 原文地址:https://www.cnblogs.com/eleven24/p/8808444.html
Copyright © 2011-2022 走看看