PHP用多列数组中的值替换字符串

时间:2017-04-04 14:59:24

标签: php arrays

PHP用多个数组中的值替换字符串。

例如,我有这样的字符串:Hello [%A%] [%B%]

我有这样的数组:

Array
(
    [A] => Array
        (
            [0] => John
            [1] => Sam
        )

    [B] => Array
        (
            [0] => Taylor
            [1] => luke    
        )
)

我希望像这样的数组生成输出:

Array
(
   [0] => Hello John Taylor
   [1] => Hello Sam luke
)

1 个答案:

答案 0 :(得分:0)

$template = "Hello [%A%] [%B%]";

$array = array(
    "A" => array("John", "Sam"),
    "B" => array("Taylor", "luke"),
);

$new_array = array();

foreach($array as $key => $values)
{
    foreach($values as $key2 => $value)
    {
        if(empty($new_array[$key2]))
        {
            $new_array[$key2] = $template;
        }

        $new_array[$key2] = str_replace("[%".$key."%]", $value, $new_array[$key2]);
    }
}

print_r($new_array);

它返回:

Array
(
    [0] => Hello John Taylor
    [1] => Hello Sam luke
)