【问题标题】:php - Merge two arrays and replace themphp - 合并两个数组并替换它们
【发布时间】:2012-06-18 13:28:49
【问题描述】:

我想合并两个数组并将文本替换为strtr函数。

我以前用过这个

$text = "cat cow";
$array = array(
"cat" => "dog",
"cow" => "bull"
);
$output = strtr($text, $array);

这返回了dog bull...

现在我有两个这样的数组...

$a = array("cat", "dog");
$b = array("dog", "bull");

两个数组都有要替换的值

现在,如何将它们组合并替换?我尝试了$array = $a + $barray_combine,但它们都不起作用......

请帮忙...

【问题讨论】:

标签: php arrays strtr


【解决方案1】:

我认为两个数组一定是

$a = array("cat", "cow");
$b = array("dog", "bull");

你可以使用

$c = array_combine($a, $b);
$output = strtr($text, $c);

【讨论】:

    【解决方案2】:

    我不知道你是如何尝试的。

    $text = "cat cow";
    $array = array(
    "cat" => "dog",
    "cow" => "bull"
    );
    
    $text = "cat cow";
    
    $array = array("cat" => "dog",
    "cow" => "bull"
    );
    $output = strtr($array, $array);
    echo $output;
    //output -> dog bull
    
    
    $a = array("cat", "cow");
    $b = array("dog", "bull");
    $c = array_combine($a,$b);
    print_r($c);
    $output1 = strtr($text, $c);
    echo $output1;
    //output -> dog bull
    

    我认为上面的代码可以为您提供所需的输出。

    我认为你使用了错误的数组 检查 $a 和 $b 数组 希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      你的意思是合并它们得到数组('cat','dog','bull')?如果是这样就这样做:

      $array = array_unique(array_merge($a,$b));
      

      【讨论】:

      • 有人能解释一下为什么是-1吗?这个问题/有点模棱两可,这很可能是一个正确的答案。
      • 确实,我相信我完全误解了这个问题。与其退出并删除它,我会把它留在这里,以防有人不小心读到它并帮助他们。无论哪种方式,感谢@EricH 要求解释。
      • 没问题。我继续为您的答案 +1,因为我发现它很有用。
      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 2017-11-22
      • 2021-01-02
      相关资源
      最近更新 更多