如果使用array_intersect()
函數(shù)時(shí)無(wú)效,可能有以下幾個(gè)原因:
array_map()
函數(shù)將字符串轉(zhuǎn)換為數(shù)字。$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]
請(qǐng)確保比較的數(shù)據(jù)類(lèi)型是一致的,并且按照您的需求使用適當(dāng)?shù)谋容^函數(shù)。