首页 > 解决方案 > 如何将输入值作为数组传递,而不是只传递一个在 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']。如何修改代码来做到这一点?

标签: phparrays

解决方案


我只是稍微修改了我的代码,我回答了你之前的问题。

添加了一个 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


推荐阅读