【问题标题】:PHP: How do you generate all possible combinations of values in an array? [duplicate]PHP:如何在数组中生成所有可能的值组合? [复制]
【发布时间】:2016-09-26 22:21:40
【问题描述】:

可能重复:
algorithm that will take numbers or words and find all possible combinations

如果我有一个数组,例如:

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

如何创建一个包含这 4 个值的所有可能组合的新数组,例如

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

谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

    这是另一种方式。

    此函数以基数递增([数组中的元素数])

    并使用 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
    【解决方案2】:

    你应该使用递归函数

    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);
    

    【讨论】:

    • 这是在 Internet 上找到的唯一真正满足我需要的方法!
    猜你喜欢
    • 2017-04-16
    • 2022-01-18
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2019-04-06
    • 2017-09-15
    • 2012-06-05
    相关资源
    最近更新 更多