PHP 从替代品中将文本替换为随机数组

PHP Replace text to random array from substitutes

如何在 $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;
?>

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

您的 $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);

你也可以这样做。

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

foreach($substitutes as $city=>$cities){

  $results[] = $substitutes[$city][array_rand($cities)];

}

echo '<pre>';
print_r($results);
echo '</pre>';

这将输出:

Array
(
    [0] => Atlanta
    [1] => Bandung
    [2] => Miami
    [3] => Hai Phong
)

您可以添加此行,如果需要,它会将其输出为字符串。

$string = implode(' - ', $results);
echo $string;

像这样:

Atlanta - Bandung - Miami - Hai Phong

祝你好运!

试试这个

 <?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) {
    $element = $choices[0];
    $elements=explode(',',$element);
    $randomElement = $elements[array_rand($elements, 1)];


        $placeholders= str_replace($key, $randomElement ,$placeholders);

    }
    echo $placeholders;
    ?>

它将产生如下输出

Orlando - Bandung - Tampa - Hai Phong

如何使这个旋转结果独一无二?