PHP:如何生成数组中所有可能的值组合? [英] PHP: How do you generate all possible combinations of values in an array?

查看:267
本文介绍了PHP:如何生成数组中所有可能的值组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
将采用数字或单词和找到所有可能的组合

Possible Duplicate:
algorithm that will take numbers or words and find all possible combinations

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

If I have an array such as:

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

如何使用这4个值的所有可能组合创建新数组,例如

How would I create a new array with all possible combinations of those 4 values such as

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

谢谢!

推荐答案

这是另一种方法.

此函数以base([[数组中的元素数])

This function increments in base( [number of elements in array] )

并使用strtr函数换出字符串中的字符.

and uses the strtr function to swap out the characters for strings.

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

这似乎也比下面的递归示例要快得多.

This also seems to be significantly faster than the recursive example below.

在我的服务器上使用microtime(),此代码将在0.072862863540649秒内运行

Using microtime() on my server this code runs in 0.072862863540649 seconds

下面的递归示例耗时0.39673089981079秒.

The recursive example below takes 0.39673089981079 seconds.

快138%!

这篇关于PHP:如何生成数组中所有可能的值组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆