我有一个字符串:{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}
!
我想知道是否有人可以帮助我解决一个返回所有可能性数组的函数?或者至少提供有关如何获取它们以及使用哪些 PHP 函数的逻辑?
谢谢
嵌套foreach
循环。
foreach($greetings as greeting)
foreach($titles as title)
foreach($names as $name)
echo $greeting,' to you, ',$title,' ',$name;
您可以通过预先对数组进行排序并更改前三行的顺序来调整它们出现的顺序
更新
这就是我想出的使用递归函数
它假设您使用正则表达式将数据保存在类似这样的地方,然后展开这应该很容易获得:
$data = array(
array("Hello","Howdy","Hola"),
array(" to you, "),
array("Mr.", "Mrs.", "Ms."),
array(" "),
array("Smith","Williams","Austin"),
array("!")
);
现在这里是功能
function permute(&$arr, &$res, $cur = "", $n = 0){
if ($n == count($arr)){
// we are past the end of the array... push the results
$res[] = $cur;
} else {
//permute one level down the array
foreach($arr[$n] as $term){
permute($arr, $res, $cur.$term, $n+1);
}
}
}
这是一个示例调用:
$ret = array();
permute($data, $ret);
print_r($ret);
产生输出
Array
(
[0] => Hello to you, Mr. Smith!
[1] => Hello to you, Mr. Williams!
[2] => Hello to you, Mr. Austin!
[3] => Hello to you, Mrs. Smith!
[4] => Hello to you, Mrs. Williams!
[5] => Hello to you, Mrs. Austin!
[6] => Hello to you, Ms. Smith!
[7] => Hello to you, Ms. Williams!
[8] => Hello to you, Ms. Austin!
[9] => Howdy to you, Mr. Smith!
[10] => Howdy to you, Mr. Williams!
[11] => Howdy to you, Mr. Austin!
[12] => Howdy to you, Mrs. Smith!
[13] => Howdy to you, Mrs. Williams!
[14] => Howdy to you, Mrs. Austin!
[15] => Howdy to you, Ms. Smith!
[16] => Howdy to you, Ms. Williams!
[17] => Howdy to you, Ms. Austin!
[18] => Hola to you, Mr. Smith!
[19] => Hola to you, Mr. Williams!
[20] => Hola to you, Mr. Austin!
[21] => Hola to you, Mrs. Smith!
[22] => Hola to you, Mrs. Williams!
[23] => Hola to you, Mrs. Austin!
[24] => Hola to you, Ms. Smith!
[25] => Hola to you, Ms. Williams!
[26] => Hola to you, Ms. Austin!
)
我知道这有点晚了,但如果你还在寻找更好的解决方案,你可以看看这个:ChillDevSpintax。