php - 在 PHP 中使用 array_walk 时,如何将输入值作为数组传递而不是仅传递一个值?

标签 php arrays

这里我用 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

https://3v4l.org/LhXa3

关于php - 在 PHP 中使用 array_walk 时,如何将输入值作为数组传递而不是仅传递一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760141/

相关文章:

php - 常量问题和连接到数据库 PHP

c - 使用链表实现社区云

php - 如何过滤MySQL日期?

php - SQL JOIN 语句 - 导出前生成数据

javascript - 为什么我的 jQuery .map 不能在这里组合我的数组?

Javascript:根据用户输入显示随机图像

ruby-on-rails - ruby 重新排序日期数组,字符串部分保留空字符串

php - MySql 结果为数组

php - 使用php文件上传错误

php - 用于 JSON 响应的 Laravel 演示器