Reputation: 690
I have 2 multidimensional arrays and I want to get the 1st array where the value of [file]
key in array 1 is equal to value of [folder_name]
key in array 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',
],
];
I have tried while looping 2 arrays and getting to one array but it is not success.
Upvotes: 3
Views: 129
Reputation: 350242
To avoid a double loop that gives a time complexity of O(n²), you could first create the set of "folder_name" values (as keys), and then use that to filter the first array. Both these operations have a time complexity of O(n) which is certainly more efficient for larger arrays:
$result = [];
$set = array_flip(array_column($arr2, "folder_name"));
foreach ($arr1 as $elem) {
if (isset($set[$elem["file"]])) $result[] = $elem;
}
$result
will have the elements of $arr1
that meet the requirement.
Upvotes: 3
Reputation: 2866
$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 contains the resultant array.
Upvotes: 1
Reputation: 4423
We can iterate both arrays inside each other to check until we have a match.
Please be aware that this shows only the first match. If you want to keep all matches you should use another helper array
to store first array values that matches to second 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;
}
}
}
Upvotes: 3