[英]permutation/generate combination prefix and suffix
我有一个前缀数组,一个基本单词数组和一个后缀数组。 我希望看到可以进行的每种组合。
例:
prefixes: 1 2
words: hello test
suffixes: _x _y
Results:
1hello_x
1hello_y
1hello
1test_x
1test_y
1test
1_x
1_y
1
2hello_x
2hello_y
2hello
2test_x
2test_y
2test
2_x
2_y
2
hello_x
hello_y
hello
test_x
test_y
test
_x
_y
y
我怎样才能做到这一点?
编辑:感谢所有的答复,我正在通过解决方案,但似乎如果没有前缀,那么它将无法组合。 即使没有任何前缀,它仍应经过基本单词和后缀。
这应该可以帮助您入门:
http://ask.amoeba.co.in/php-combinations-of-array-elements/
//$a = array("1", "2");
$b = array("hello", "test");
$c = array("_x", "_y");
if(is_array($a)){
$aG = array($a,$b, $c);
}else{
$aG = array($b, $c);
}
$codes = array();
$pos = 0;
generateCodes($aG);
function generateCodes($arr) {
global $codes, $pos;
if(count($arr)) {
for($i=0; $i<count($arr[0]); $i++) {
$tmp = $arr;
$codes[$pos] = $arr[0][$i];
$tarr = array_shift($tmp);
$pos++;
generateCodes($tmp);
}
} else {
echo join("", $codes)."<br/>";
}
$pos--;
}
结果:
1hello_x
1hello_y
1test_x
1test_y
2hello_x
2hello_y
2test_x
2test_y
for each $prefix in $prefixes {
for each $base in $basewords {
for each $suffix in $suffixes {
echo $prefix.$base.$suffix."\n"
}}}
这将满足您的要求,我相信在php中没有内置函数可以做到这一点(尽管python中有)
function combineAll ($prefixes, $words, $suffixes)
{
$combinations = array ();
foreach ($prefixes as $prefix)
{
foreach ($words as $word)
{
foreach ($suffixes as $suffix)
{
$combinations[] = $prefix.$word.$suffix;
}
}
}
return $combinations;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.