php中array_intersect使用無(wú)效怎么解決

PHP
小億
100
2024-01-24 23:14:57

如果使用array_intersect()函數(shù)時(shí)無(wú)效,可能有以下幾個(gè)原因:

  1. 數(shù)組中的值是字符串,但是存儲(chǔ)的是數(shù)字形式。這種情況下,您可以使用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);
  1. 數(shù)組中的值是對(duì)象,但是對(duì)象的比較是通過(guò)引用,而不是值。如果想比較對(duì)象的屬性值,可以通過(guò)自定義一個(gè)匿名函數(shù)來(lái)實(shí)現(xiàn)。
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ù)。

0