检查一个数组中某个键的值是否等于另一个数组中不同键的值

Check if the value of a key in one array is equal to the value of different key in another array

我有 2 个多维数组,我想获取第一个数组,其中数组 1 中 [file] 键的值等于数组 2 中 [folder_name] 键的值

$arr1 = [
    [
        'is_dir'      => '1',
        'file'        => 'hello member',
        'file_lcase'  => 'hello member',
        'date'        => '1550733362',
        'size'        => '0',
        'permissions' => '',
        'extension'   => 'dir',
    ],
    [
        'is_dir'      => '1',
        'file'        => 'in in test',
        'file_lcase'  => 'in in test',
        'date'        => '1550730845',
        'size'        => '0',
        'permissions' => '',
        'extension'   => 'dir',
    ]
];

$arr2 = [
    [
        'dic_id'      => '64',
        'folder_name' => 'hello member',
        'share_with'  => '11',
    ],
    [
        'dic_id'      => '65',
        'folder_name' => 'hello inside',
        'share_with'  => '11',
    ],
    [
        'dic_id'      => '66',
        'folder_name' => 'in in test',
        'share_with'  => '11',
    ],
];

我试过循环 2 个数组并到达一个数组,但没有成功。

我们可以在彼此内部迭代两个数组以进行检查,直到找到匹配项。

请注意,这仅显示第一场比赛。如果您想保留所有匹配项,您应该使用另一个助手 array 来存储与第二个数组匹配的第一个数组值。

foreach ($array1 as $key => $value) {
    foreach ($array2 as $id => $item) {
        if($value['file'] == $item['folder_name']){
            // we have a match so we print out the first array element
            print_r($array1[$key]);
            break;
        }
    }
}
$arr1 = array();
$arr2 = array();
$arr3 = array();
$arr1[] = array('is_dir'=>'1','file'=>'hello member','file_lcase'=>'hello member','date'=>'1550733362','size'=>'0','permissions'=>'','extension'=>'dir');
$arr1[] = array('is_dir'=>'1','file'=>'in in test','file_lcase'=>'in in test','date'=>'1550730845','size'=>'0','permissions'=>'','extension'=>'dir');
$arr2[] = array('dic_id'=>'64','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'65','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'66','folder_name'=>'in in test','share_with'=>'11');

foreach($arr1 as $a){
    foreach($arr2 as $a2){
        if($a['file'] == $a2['folder_name']){
            $arr3[]=$a;
        }
    }
}
$arr3 = array_map("unserialize", array_unique(array_map("serialize", $arr3))); // remove duplicates
var_dump($arr3);

$arr3 包含结果数组。

为了避免时间复杂度为 O(n²) 的双循环,您可以先创建 "folder_name" 值集(作为键),然后然后用它来过滤第一个数组。这两个操作的时间复杂度都是 O(n),这对于更大的数组来说肯定更有效:

$result = [];
$set = array_flip(array_column($arr2, "folder_name"));
foreach ($arr1 as $elem) {
    if (isset($set[$elem["file"]])) $result[] = $elem;
}

$result会有$arr1的元素满足要求。