I have the following two arrays:
$a1 = [56,60];
$a2 = [60 => 'aa', 61 => 'bb', 62 => 'cc', 63 => 'dd'];
I'm trying to apply array_map
to construct a new array that would look like this:
Array
(
[56] =>
[60] => aa
)
Basically what I need is to go through the first array, if I find it in the second array, I'll grab its corresponding value, otherwise, set it to an empty string. Is array_map
the best way to go about this?
A simple loop seems easiest to me, using array_key_exists()
$a1 = [56,60];
$a2 = [60 => 'aa',61 => 'bb',62 => 'cc',63 => 'dd'];
$new = [];
foreach ( $a1 as $key ) {
if ( array_key_exists($key, $a2) ) {
$new[$key] = $a2[$key];
}
}
print_r($new);
RESULT
Array
(
[60] => aa
)
Or if you really want a blank occurance, this would work
$a1 = [56,60];
$a2 = [60 => 'aa',61 => 'bb',62 => 'cc',63 => 'dd'];
$new = [];
foreach ( $a1 as $key ) {
$new[$key] = array_key_exists($key, $a2) ? $a2[$key] : null;
}
print_r($new);
RESULT
Array
(
[56] =>
[60] => aa
)
Or even
$a1 = [56,60];
$a2 = [60 => 'aa',61 => 'bb',62 => 'cc',63 => 'dd'];
$new = [];
foreach ( $a1 as $key ) {
$new[$key] = $a2[$key] ?? null;
}
print_r($new);
RESULT
Array
(
[56] =>
[60] => aa
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.