PHP:如何生成数组中所有可能的值组合?

问题描述:

可能重复:
algorithm that will take numbers or words and find all possible combinationsPHP:如何生成数组中所有可能的值组合?

如果我有一个数组,如:

array('a', 'b', 'c', 'd'); 

我将如何创建与4个值的所有可能组合的新数组如

aaaa, aaab, aaac, aaad ... dddb, dddc, dddd 

谢谢!

这里的另一种方式。

此功能的增量在碱

([在数组元素的数]),并使用strtr函数的效率函数换出的字符的字符串。

function everyCombination($array) { 

    $arrayCount  = count($array); 
    $maxCombinations = pow($arrayCount, $arrayCount); 
    $returnArray  = array(); 
    $conversionArray = array(); 

    if ($arrayCount >= 2 && $arrayCount <= 36) 
    { 
     foreach ($array as $key => $value) { 
      $conversionArray[base_convert($key, 10, $arrayCount)] = $value; 
     } 

     for ($i = 0; $i < $maxCombinations; $i++) { 
      $combination = base_convert($i, 10, $arrayCount); 
      $combination = str_pad($combination, $arrayCount, "0", STR_PAD_LEFT); 
      $returnArray[] = strtr($combination, $conversionArray); 
     } 

     return $returnArray; 
    } 

    echo 'Input array must have between 2 and 36 elements'; 
} 

则...

print_r(everyCombination(array('a', 'b', 'c', 'd'))); 

这也似乎比下面的递归例如更快的是显著。我的服务器上

使用microtime中()这个代码0.072862863540649秒

下面的递归示例采用0.39673089981079秒运行。

快138%!

+1

这工作完美 - 谢谢! – user1926784

+1

这是一段很棒的代码。 +1 – Peter

您应该使用递归函数

function perm($arr, $n, $result = array()) 
{ 
    if($n <= 0) return false; 
    $i = 0; 

    $new_result = array(); 
    foreach($arr as $r) { 
    if(count($result) > 0) { 
     foreach($result as $res) { 
       $new_element = array_merge($res, array($r)); 
       $new_result[] = $new_element; 
      } 
     } else { 
      $new_result[] = array($r); 
     } 
    } 

    if($n == 1) return $new_result; 
    return perm($arr, $n - 1, $new_result); 
} 

$array = array('a', 'b', 'c', 'd'); 
$permutations = perm($array, 4); 
print_r($permutations); 
+1

这是在互联网上找到的唯一方法,它实际上做我所需要的! – Dejv