我有2个数组,其中一个占位符是另一个数组中的键
arr1 = array(
"id" => "{{verticalId}}",
"itemPath" => "{{verticalId}}/{{pathId}}/");
arr2 = array(
"verticalId" => "value1",
"pathId" => "value2");
那么如何在arr1
上运行并用arr2
的值替换占位符?
答案 0 :(得分:5)
foreach ($arr1 as $key => &$value) {
$value = preg_replace_callback('/\{\{(.*?)\}\}/', function($match) use ($arr2) {
return $arr2[$match[1]];
}, $value);
}
答案 1 :(得分:0)
当然,这是一种方法。它需要一点爱,而PHP 5.3 +
<?php
$subject = array(
'id' => '{{product-id}}'
);
$values = array(
'product-id' => 1
);
array_walk($subject, function( & $item) use ($values) {
foreach($values as $template => $value) {
$item = str_replace(
sprintf('{{%s}}', $template),
$value,
$item
);
}
});
var_dump(
$subject
);