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

时间:2019-02-21 10:21:33

标签: php arrays multidimensional-array matching

我有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个数组并进入一个数组,但这并不成功。

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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满足要求的元素。

答案 2 :(得分: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包含结果数组。