2011-03-06 100 views
0

我有一个前缀数组,基数词数组和后缀数组。我希望看到可以制作的每个组合。排列/生成组合前缀和后缀

例子:

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 

我怎样才能做到这一点?

编辑:感谢所有的答复,我正在通过解决方案,但似乎如果没有前缀,那么它将失败的组合。它应该仍然通过基本词汇和后缀,即使没有任何前缀。

回答

0
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; 
} 
+0

请参阅编辑。 – ParoX 2011-03-06 21:46:49

+0

如果我只是添加'array_push($ prefixes,“”);'''array_push($ words,“”);''array_push($ prefixes,“”);'然后它会做我需要的。另外请注意,你有$后缀的参数,而不是后缀 – ParoX 2011-03-06 21:55:18

+0

叹息,请张贴'充分'的问题,而不是多次改变它。 – 2011-03-06 22:00:36

0

这应该让你开始:

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

+0

请参阅编辑。 – ParoX 2011-03-06 21:47:14

+0

编辑允许可选$ a – 2011-03-06 21:54:53

0
for each $prefix in $prefixes { 
for each $base in $basewords { 
for each $suffix in $suffixes { 
echo $prefix.$base.$suffix."\n" 
}}} 

这会做你想要什么,我相信没有内置函数在PHP这样做(尽管在Python)

+0

请参阅编辑。 – ParoX 2011-03-06 21:46:18