在PHP中使用数组,如何始终通过key2更改key1或通过key1更改key2?

时间:2017-06-01 05:50:25

标签: php arrays if-statement replace preg-match

我之前的代码是一个rand,它与我当前的意图无关,每当我通过数组的其他值找到值时都会替换它。

$myWords=array(
    array('funny','sad'),
    array('fast','slow'),
    array('beautiful','ugly'),
    array('left','right'),
    array('5','five'),
    array('strong','weak')
);

$mycontentmixed = rewrite3($myVar, $myWords);
$myVar = 'This girl is very funny and fast and kick to left';

当系统找到数组中包含的任何键的值时,总是切换到另一个值,我已经准备好了这个系统,但它确实有一个rand,有时会落在找到的相同键上,并且在50%的在没有价值的情况下,我总是想改变。

我想改为:

output: 'This girl is very sad and slow and kick to right';

或者,如果您找到另一个密钥:

$myVar = 'This girl is very sad and slow and kick to right';

切换到:

Output: 'This girl is very funny and fast and kick to left';

当在$ myVar变量中找到其中一个键时,总是进行另一个键的交换。

感谢。

2 个答案:

答案 0 :(得分:1)

此代码将执行此操作:

$myWords=array(
array('funny','sad')
,array('fast','slow')
,array('beautiful','ugly')
,array('left','right')
,array('5','five')
,array('strong','weak')
);


$myVar = 'This girl is very funny and fast and kick to left';

foreach ($myWords as $key => $val) {
  if (strpos($myVar, $val[0]) !== FALSE) {
    $myVar = str_replace($val[0], $val[1], $myVar);
  }
  else {
    $myVar = str_replace($val[1], $val[0], $myVar);
  }
}
echo $myVar;

希望这有帮助。

答案 1 :(得分:1)

Barmar是对的,strtr()是完成此任务的正确功能。由于$myWords数组的结构不能立即用于strtr(),因此在准备过程中需要进行6次函数调用。如果在$myWords时声明strtr(),则可以避免/减少这六个调用。

基本上,这可以是一个单功能的解决方案,应该使用而不是迭代的条件检查str_replace()

方法:

$myWords=array(
    array('funny','sad'),
    array('fast','slow'),
    array('beautiful','ugly'),
    array('left','right'),
    array('5','five'),
    array('strong','weak')
);

// prepare values from $myWords for use with strtr()
$replacements=array_combine(array_column($myWords,0),array_column($myWords,1))+
              array_combine(array_column($myWords,1),array_column($myWords,0));
echo strtr($myVar,$replacements);

输入/输出:

   $myVar='This girl is very funny and fast and kick to left';
//outputs: This girl is very sad and slow and kick to right

   $myVar='This girl is very sad and slow and kick to right';
//outputs: This girl is very funny and fast and kick to left

   $myVar='I was beautiful and strong when I was 5 now I\'m ugly and weak';
//outputs: I was ugly and weak when I was five now I'm beautiful and strong

唯一的额外步骤是阵列准备。我无法使用array_merge(),因为数字字符串(5)会在此过程中被清除。这就是+连接的原因。