php - 如何将输入值作为数组传递,而不是只传递一个在 PHP 中使用 array_walk 的值?
问题描述
在这里,我在 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
推荐阅读
- python - 制作课程,放入字典然后放入列表
- java - 更改 RecyclerView android Kotlin 上仅选定项目的文本颜色
- c# - MS DI how to configure services using information known only at runtime
- flutter - 是否可以使用其他提供程序进行 Firebase 身份验证?
- flutter - 颤动中当前页面路由上方的气泡通知
- multithreading - JavaFX - 简单翻转卡(延迟 2 秒更改两个图像)
- pine-script - Pinescript TradingView:有条件和止损的卖单
- amazon-web-services - 所有 AWS EC2 实例是否默认都有 AWS shield?
- android - React-native/Android Studio:错误:没有这样的属性:类的 GradleVersion:JetGradlePlugin
- ruby-on-rails - ActiveModelSerializer:如何为自定义属性添加关联?