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

3
我有2个多维数组,我想获取第一个数组中 [file] 键的值等于第二个数组中 [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',
    ],
];

我尝试过循环遍历两个数组并将它们合并为一个数组,但是没有成功。


结果应该是什么样子? - Yoshi
@sampath 给出你期望的答案,以帮助更好地描述情况。 - hazelcodes
@hazelcodes 我期望得到与array1相同的数组。 - Sampath Wijesinghe
@sampathwijesinghe 请检查我下面的答案 - Edison Biba
@sampathwijesinghe “我期望得到与array1相同的数组”这句话并没有太多意义,因为如果是这样的话,你可以直接使用array1。请详细说明。 - Yoshi
确认您想要保留在array1中所有包含在array2中以“folder_name”为名称的“file”的数组。 - hazelcodes
3个回答

3
我们可以互相迭代这两个数组,以此来检查是否有匹配项。
请注意,这只显示第一个匹配项。如果您想保留所有匹配项,应使用另一个帮助程序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;
        }
    }
}

3
为了避免双重循环,时间复杂度为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元素。


1
$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 包含结果数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接