php - 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;
?>
还有一些输出:达拉斯-雅加达-迈阿密-曼德勒
解决方案
您的$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);
推荐阅读
- javascript - v-list-item-group 一次全选/取消全选
- laravel - Laravel Blade 使用 VueJS 在表格内渲染表格
- git - 如果我从一个分支中删除一个文件并对具有该文件的目标分支进行 PR,它是否也会从目标分支中删除该文件?
- javascript - 为什么anime.js在vuejs中点击不起作用?
- javascript - 如何在javascript中将未定义的数组转换为数组字符串
- python - 如何将 kwargs 传递给 argparse
- c# - C# 复选框优化
- c# - 读取 .der 文件私钥 C#
- java - MongoDB Java 驱动程序 @Discriminator @BsonDiscriminator 注解
- docker - circleci docker 的 mysql 和 php 图像在创建时失败