如何替换来自两个不同多维数组的字符串?

时间:2019-01-27 23:25:01

标签: php arrays str-replace

我尝试使用str_replace和分类数组来替换来自两个不同多维数组的字符串。

我尝试两次使用array_walk_recursive:一次在外面,一次在里面,如下所示

$array1 = [
    'key1' => [
        'first string'
    ],
    'key2' => [
        'second array'
    ]
];

$array2 = [
    'key1' => [
        'new string from second array'
    ],
    'key2' => [
        'second key in this other multidimensional array'
    ]
];

$outer_string = "Hello, this is my first string\nAnd here you can see another string from my second array";

echo array_walk_recursive($array1, function(&$e1, $i1) {
    return array_walk_recursive($array2, function(&$e2, $i2) {
        return str_replace($e1, $e2, $outer_string);
    });
});

我希望它遍历第一个数组中的每个键,并将其替换为第二个数组中相同键的值。字符串应为"Hello, this is my new string from second array\nAnd here you can see another string from my second key in this other multidimensional array"

1 个答案:

答案 0 :(得分:0)

这个问题的一个相当简单的解决方案是遍历两个数组,构建一个替换对数组(基于两个数组之间的匹配键),然后将该数组传递给strtr

$replacements = array();
foreach ($array1 as $k => $v) {
    $replacements[$v[0]] = $array2[$k][0];
}
echo strtr($outer_string, $replacements);

输出:

Hello, this is my new string from second array
And here you can see another string from my second key in this other multidimensional array

Demo on 3v4l.org