简体   繁体   中英

How to match and replace one array values to another array keys if they both start with the same letters?

I have two arrays:

$array_one = array('AA','BB','CC');

And:

$replacement_keys = array
 (
 ""=>null,
 "BFC"=>'john',
 "ASD"=>'sara',
 "CSD"=>'garry'
);

So far I've tried

array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.

My goal is to make a final output:

$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);

In other words to find a matching first letter and than replace the key with the value of the first array.

Any and all help will be highly appreciated.

Here is a solution keeping both $replacement_keys and $array_one intact

$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
    $index = array_search(substr($key, 0, 1), $tempArray);
    if ($index !== false) {
        $new_array[$array_one[$index]] = $replacement_key;
    } else {
        $new_array[$key] = $replacement_key;
    }
}

Here is a link https://3v4l.org/fuHSu

You can approach like this by using foreach with in_array

$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
 $split = str_split($k)[0];
 $split .= $split;
 in_array($split, $a1) ? ($r[$split] = $v)  : ($r[$k] = $v);
}

Working example:- https://3v4l.org/ffRWY

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM