zoukankan      html  css  js  c++  java
  • array_udiff、array_udiff_assoc、array_udiff_uassoc 使用方法

     
    <?php
    
    // array_udiff 用自定义函数比较数组的差值(array_diff 使用内置函数)
    // 使用该函数我们通过进行更复杂的比较
    
    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),
    ];
    
    $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_udiff($array1, $array2, 'compare_area'));
    
    // 返回数据差集, 同时检查键值(键的比较使用内置方法)
    var_dump(array_udiff_assoc($array1, $array2, 'compare_area'));
    
    // 返回数据差集, 同时检查键值(键的比较使用自定义函数)
    var_dump(array_udiff_uassoc($array1, $array2, 'compare_area', 'compare_key'));
    array(1) {
      ["a"]=>
      object(Rectangle)#1 (2) {
        ["width"]=>
        int(1)
        ["height"]=>
        int(2)
      }
    }
    array(2) {
      ["a"]=>
      object(Rectangle)#1 (2) {
        ["width"]=>
        int(1)
        ["height"]=>
        int(2)
      }
      ["b"]=>
      object(Rectangle)#2 (2) {
        ["width"]=>
        int(2)
        ["height"]=>
        int(3)
      }
    }
    array(2) {
      ["a"]=>
      object(Rectangle)#1 (2) {
        ["width"]=>
        int(1)
        ["height"]=>
        int(2)
      }
      ["b"]=>
      object(Rectangle)#2 (2) {
        ["width"]=>
        int(2)
        ["height"]=>
        int(3)
      }
    }
    

      

  • 相关阅读:
    Gradle命令行操作
    Web项目构建
    Java构建
    任务操纵
    mysql 查看当前使用的配置文件my.cnf的方法(推荐)
    mysql命令gruop by报错this is incompatible with sql_mode=only_full_group_by
    Oracle注入速查表
    git 初始化项目操作
    mybatis 一次执行多条SQL MySql+Mybatis+Druid之SqlException:sql injection violation, multi-statement not allow
    文件存储 FileUtil FileBaseDto
  • 原文地址:https://www.cnblogs.com/eleven24/p/8808316.html
Copyright © 2011-2022 走看看