检查两个数组中是否重复 key/value

Check if duplicate key/value across two arrays

场景:

输入:教师职称数组和规模

A1:
[designation] => Array
    (
        [0] => 24
        [1] => 25
        [2] => 26
        [3] => 27
        [4] => 24
        [5] => 25
    )

[grade_scale] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 1
        [5] => 10
    )

现在,A1 数组中有一个相同的名称重复了两次,这很好,因为 A2 中可以存在不同等级的相同名称。

但是,如果出现 2 个相同的名称,那么它们的等级应该不同。

在上述情况下,指定 24 和 25 是重复的。

目前我尝试过的:

$counts = array_count_values($a1);


$filtered = array_filter($a1, function ($value) use ($counts) {
    return $counts[$value] > 1;
});             

$filtered 数组给我重复项的索引号。

$filtered
(
    [0] => 24
    [1] => 25
    [4] => 24
    [5] => 25
)

我想检查 A2 数组中相同索引处的值是否也重复。在这种情况下,指定 24 在 A2 中具有相同索引的相同等级。

to check whether the values at same indexes in A2 array are duplicate too

使用array_filterarray_count_valuesarray_intersect_keyarray_fliparray_unique函数的解决方案:

$a1 = [0 => 24, 1 => 25, 2 => 26, 3 => 27, 4 => 24, 5 => 25];
$a2 = [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 1, 5 => 10];

// getting all duplicate designation values from $a1 array
$counts = array_filter(array_count_values($a1), function($v){ return $v > 1; });
$dup_designations = [];

// iterating through all duplicate 'designation' items from $a1  array
foreach ($counts as $k => $v) {
    // obtaining respective items from $a2 array by key intersection 
    // with  current designation items sequence  
    $grades = array_intersect_key($a2, array_flip(array_keys($a1, $k)));

    // check if found duplicates within $a2 array have the same value
    if (count(array_unique($grades)) != count($grades)) {
        $dup_designations[] = $k;
    }
}

print_r($dup_designations);

输出:

Array
(
    [0] => 24
)