问题
I have 2 arrays, I would like to use the keys from the 1st array to search for matched keys from the 2nd array and return those keys from the 2nd array with the values of the second array.
expected result: Array ( 'Intermediary/contract/{contract:id}/bank-accounts'[2] 'Manager/action/{action:id}/bank-bills'[2] )
$arrayOne = [
'/Intermediary/contract//bank-accounts'[2]
'/Manager/action//bank-bills'[2]]
$arrayTwo = [
'/Intermediary/contract/{contract:id}/bank-accounts',
'/Manager/action/{action:id}/bank-bills',
]
So far I've tried, among others,
foreach ($array1 as $key => $value) {
$results = preg_grep('/$key/', $array2);
}
回答1:
Those are values and not keys in your example arrays.
First get rid of all of the {.....}
from $arrayTwo
and compute the intersection (same entries) with $arrayOne
. Since the keys are preserved in the array that has been replaced you can compute the intersection of keys with $arrayTwo
:
$result = array_intersect_key(
array_intersect(preg_replace('/\{[^}]+\}/', '', $arrayTwo), $arrayOne),
$arrayTwo
);
Here's a Demo.
If you really need the keys then the answer is slightly different getting the keys as an array:
$result = array_intersect_key(
array_keys($arrayTwo),
array_intersect(preg_replace('/\{[^}]+\}/', '', array_keys($arrayTwo)),
array_keys($arrayOne))
);
Here's a Demo.
To do it with a loop:
foreach($arrayTwo as $k => $v) {
if(in_array(preg_replace('/\{[^}]+\}/', '', $k), array_keys($arrayOne))) {
$result[] = $k;
}
}
If for whatever reason you need them as keys again, there is array_flip.
来源:https://stackoverflow.com/questions/60935815/how-to-match-keys-from-one-array-to-another-and-return-keys-from-the-other