我有一个字符串:{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!
我想知道有没有人能帮我写一个函数,它会返回一个包含所有可能性的数组?或者至少提供了如何获取它们以及使用哪些PHP函数的逻辑?
谢谢
发布于 2013-05-19 15:30:31
嵌套的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!
)发布于 2014-01-25 04:45:02
我知道现在有点晚了,但是如果你还在寻找一个更好的解决方案,你可以看看这个:ChillDevSpintax。
https://stackoverflow.com/questions/16632247
复制相似问题