首页 > 解决方案 > 检查一个数组中某个键的值是否等于另一个数组中不同键的值

问题描述

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

$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 个数组并到达一个数组,但这并不成功。

标签: phparraysmultidimensional-arraymatching

解决方案


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

请注意,这仅显示第一场比赛。如果要保留所有匹配项,则应使用另一个帮助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;
        }
    }
}

推荐阅读