这里我用 PHP 创建了 Hashmap 数组。我将输入作为 $keys = str_split('cat1hen')
给出,输出为“doga@nt
”。
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$keys = str_split('cat1hen');
$output = [];
array_walk($keys,
function($item, $index) use($rule,$keys, &$output) {
if($rule[$item] == '@' && isset($keys[$index + 1])) {
$output[] = $rule[$keys[$index + 1]];
return;
}
if(isset($keys[$index - 1]) && $rule[$keys[$index - 1]] == '@') {
$output[] = '@';
return;
}
$output[] = $rule[$item];
return;
},
$keys);
echo implode($output);
我不想给出一个输入值,而是想将输入作为具有多个值的数组给出,即 $keys = ['cat1hen','cathen','hencat']
,它应该给出输出为 ['doga@nt','dogant','antdog']
。如何修改代码来做到这一点?
最佳答案
我只是稍微修改了我回答你之前问题的代码。
添加了 foreach 来循环单词。
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$orders = ['cat1hen','cathen','hencat'];
foreach($orders as $order){
$arr = str_split($order);
$str ="";
foreach($arr as $key){
$str .= $rule[$key];
}
$str = preg_replace("/(.*?)(@)(.)(.*)/", "$1$3$2$4", $str);
echo $str . "\n";
}
//doga@nt
//dogant
//antdog
关于php - 在 PHP 中使用 array_walk 时,如何将输入值作为数组传递而不是仅传递一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760141/