<?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)
}
}