如果使用array_intersect()
函数时无效,可能有以下几个原因:
- 数组中的值是字符串,但是存储的是数字形式。这种情况下,您可以使用
array_map()
函数将字符串转换为数字。
$array1 = ['1', '2', '3']; $array2 = [2, 3, 4]; $array1 = array_map('intval', $array1); $result = array_intersect($array1, $array2); print_r($result);
- 数组中的值是对象,但是对象的比较是通过引用,而不是值。如果想比较对象的属性值,可以通过自定义一个匿名函数来实现。
class Item {
private $id;
public function __construct($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
$item1 = new Item(1);
$item2 = new Item(2);
$item3 = new Item(3);
$array1 = [$item1, $item2];
$array2 = [$item2, $item3];
$result = array_intersect($array1, $array2);
print_r($result); // []
$result = array_uintersect($array1, $array2, function($a, $b) {
return $a->getId() <=> $b->getId();
});
print_r($result); // [$item2]
请确保比较的数据类型是一致的,并且按照您的需求使用适当的比较函数。