1

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

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

4

4 回答 4

1

您的$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);
于 2018-11-24T08:40:06.100 回答
0

你也可以这样做。

$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

祝你好运!

于 2018-11-24T08:50:09.270 回答
0

试试这个

 <?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
于 2018-11-24T08:53:03.490 回答
0

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

于 2018-11-26T10:16:34.577 回答