我试图在 PHP 中找到一个数组中不在另一个数组中的元素。我的印象是我应该使用array_udiff
带有自定义回调的函数。
第一个数组是具有 id 属性的对象数组。第二个数组是具有 name 属性的对象数组。名称属性在组成其名称的字符串中包含一个 ID 号。
我的目标是确保第一个数组中每个对象的 ID 在第二个数组中都有一个对应的对象,该对象在名称中包含它的 ID。这是我的代码:
<?php
class NameObj {
public $name;
function __construct($name){
$this->name = $name;
}
}
class IdObj{
public $id;
function __construct($id){
$this->id = $id;
}
}
$idArray = array(
new IdObj(1),
new IdObj(2),
new IdObj(3)
);
$nameArray = array(
new NameObj('1 - Object 1 Name'),
new NameObj('2 - Object 2 Name')
);
function custom_diff($oId, $oName){
$splitName = explode(' - ', $oName->name);
$idFromName = $splitName[0];
$id = $oId->id;
if($idFromName == $id) return 0;
return $idFromName > $id ? 1 : -1;
}
$missing_objects = array_udiff($idArray, $nameArray, 'custom_diff');
print_r($missing_objects);
?>
我希望看到一个仅包含第一个数组中的第三个对象的数组,但我得到了这个:
PHP Notice: Undefined property: IdObj::$name in /home/ubuntu/test2.php on line 33
PHP Notice: Undefined property: IdObj::$name in /home/ubuntu/test2.php on line 33
PHP Notice: Undefined property: NameObj::$id in /home/ubuntu/test2.php on line 36
PHP Notice: Undefined property: IdObj::$name in /home/ubuntu/test2.php on line 33
PHP Notice: Undefined property: IdObj::$name in /home/ubuntu/test2.php on line 33
Array
(
[1] => IdObj Object
(
[id] => 2
)
[2] => IdObj Object
(
[id] => 3
)
)
我在这里想念什么?我是否array_udiff
错误地使用了该功能?