php - 二维数组中的所有可能性

标签 php algorithm arrays

我有这个数组:

$array = array
(
    array('1', '2', '3'),
    array('!', '@'),
    array('a', 'b', 'c', 'd'),
);

我想知道子数组的所有字符组合.. 例如:

1!a
1!b
1!c
1!d
1@a
1@b
1@c
1@d
2!a
2!b
2!c
2!d
2@a
2@b
...

目前我有这段代码:

for($i = 0; $i < count($array[0]); $i++)
{
    for($j = 0; $j < count($array[1]); $j++)
    {
        for($k = 0; $k < count($array[2]); $k++)
        {
            echo $array[0][$i].$array[1][$j].$array[2][$k].'<br/>';
        }
    }
}

可以用,但我觉得它很丑,而且当我添加更多的数组时,我必须添加更多的for。我很确定有一种方法可以递归地执行此操作,但我不知道如何开始/如何进行。一点帮助可能会很好!

谢谢!

最佳答案

你可以像这样创建一个递归函数:

function combination($array, $str = '') {
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $element) {
           combination($array, $str.$element);
       }
   }
   else{
       foreach($current as $element) {
           echo $str.$element . PHP_EOL;
       }
   } 
}

然后:

combination($array);

如果你想将所有组合放在一个新数组中,而不是打印它们,请像这样扩展函数:

function combination($array, array &$results, $str = '') {
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $element) {
           combination($array, $results,  $str.$element);
       }
   }
   else{
       foreach($current as $element) {
           $results[] = $str.$element;
       }
   } 
}

$results = array();
combination($array, $results);

关于php - 二维数组中的所有可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799151/

相关文章:

php - 为旋转 slider 中的特定图层提供 id 或类

php - 在 span Clases PHP 中包装第一个和第二个单词

php - 带有 codeigniter 的 MySQL DISTINCT ...非常奇怪的行为

算法分析 - 在 O(1) 中使用冲突列表进行哈希搜索

algorithm - 为什么标准合并排序没有到位?

c# - 为相同类型的一对(循环列表)在轮播列表中查找不同类型的邻居

c++ - gcc 6 但不是 gcc 4 的灵活数组错误

php - MySQL的having子句和where子句

javascript - 使用另一个数组对固定的对象数组进行排序

php - 在 PHP 中计算数组中的项目