首页 > 解决方案 > PHP将文本从替代品替换为随机数组

问题描述

如何在 $substitutes 上用随机城市替换“City1”

<?php 
$placeholders = 'City1 - City2 - City3 - City4';
$substitutes  = [
'City1' => ['Orlando,Dallas,Atlanta,Detroit'],
'City2' => ['Jakarta,Bandung,Surabaya'],
'City3' => ['Atlanta,Tampa,Miami'],
'City4' => ['Mandalay,Caloocan,Hai Phong,Quezon City'],
];
$replacements = [];
foreach($substitutes as $key => $choices) {
    $random_key = array_rand($choices);
    $replacements[$key] = $choices[$random_key];
}
$spun = str_replace(
    array_keys($replacements),
    array_values($replacements),
    $placeholders
);
echo $spun;
?>

还有一些输出:达拉斯-雅加达-迈阿密-曼德勒

标签: phpstringstr-replace

解决方案


您的$substitutes数组未正确定义。尝试:

$substitutes = [
  'City1' => ['Orlando', 'Dallas', 'Atlanta', 'Detroit'],
  'City2' => ['Jakarta', 'Bandung', 'Surabaya'],
  'City3' => ['Atlanta', 'Tampa', 'Miami'],
  'City4' => ['Mandalay', 'Caloocan', 'Hai Phong', 'Quezon City']
]; 

或者,如果由于某种原因,您无法更改$substitutes定义方式,则可以执行以下操作将其转换为正确的形式:

$substitutes = array_map(function ($cities) {
  return explode(',', $cities[0]);
}, $substitutes);

推荐阅读