[英]How to swap element according to condition in PHP where there is array_map?
I created hashmap array in PHP and used array_map to print result. 我在PHP中创建了hashmap数组,并使用array_map打印结果。
<?php
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
echo join('', array_map(function($x) use($rule) { return $rule[$x]; },
str_split('cat1hen')));
?>
It display output as "dog@ant".But I want different output.Everytime there is expected output as "@",I want to swap "@" to swap its value with next array element. 它显示输出为“ dog @ ant”。但是我想要不同的输出。每次期望的输出为“ @”时,我都想交换“ @”以将其值与下一个数组元素交换。
It means output should be "doga@nt" instead of "dog@ant".Here position of @ is swapped with its next array element ie "a". 这意味着输出应该是“ doga @ nt”而不是“ dog @ ant”。@的位置与其下一个数组元素即“ a”交换。 The position should be swapped only when expected output is "@".
仅当预期输出为“ @”时,才应交换头寸。
I have already done this in javascript: 我已经在javascript中完成了此操作:
var rule = {
"c": "d",
"a": "o",
"t": "g",
"h": "a",
"1": "@",
"e": "n",
"n": "t"
}
function convert(str) {
let strArr = [...str];
return strArr.map((d, i, arr) => {
if (rule[d] == '@') {
return rule[arr[i + 1]];
} else if (rule[arr[i - 1]] == '@') {
return '@';
}
return rule[d];
}).join('')
}
console.log(convert("cat1hen"))
But I want to use this logic in PHP as well.I did array_map to map element in above PHP code but if else part was confusing to me.How to do that in php and print 'doga@nt'. 但是我也想在PHP中使用这种逻辑。我做了array_map来映射上面的PHP代码中的元素,但是如果其他部分让我感到困惑,如何在php中做到这一点并打印'doga @ nt'。
Using array_walk()
which gives access to the current index. 使用
array_walk()
可以访问当前索引。
$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);
// doga@nt
Maybe I have completely missed the point, but why not just implode the array and you will get the expected output. 也许我已经完全错失了要点,但是为什么不直接插入数组,您将获得预期的输出。
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$str = implode("", $rule);
echo $str; //doga@nt
An optional method is to build the array according to your string then use preg_replace to swap the positions of the letters. 可选方法是根据您的字符串构建数组,然后使用preg_replace交换字母的位置。
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$order = str_split("cat1hen");
$str ="";
foreach($order as $key){
$str .= $rule[$key];
}
$str = preg_replace("/(.*?)(@)(.)(.*)/", "$1$3$2$4", $str);
echo $str; //doga@nt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.