2010-05-09 24 views
5

我有此数组:在二维数组的所有可能性

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

而且我想知道子阵列的所有字符组合。例如:

1!a 
1!b 
1!c 
1!d 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
2!a 
2!b 
2!c 
2!d 
[email protected] 
[email protected] 
... 

目前我有这样的代码:

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/>'; 
     } 
    } 
} 

它的工作原理,但我认为这是丑陋的,当我添加更多的阵列,我必须添加更多的。我敢肯定有一种方法递归做到这一点,但我不知道如何开始/如何做到这一点。一点帮助可能会很好!

谢谢你!如果你想有一个新的阵列中的所有组合

combination($array); 

,而不是要打印出来,延伸功能:

回答

4

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

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

然后像这样:

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

请问这个不是在PHP 5突破?我的意思是,它有效......但为什么?我以为我记得读一些有关数组和对象总是得到通过引用传递现在......那不是意味着$数组被错位? – cHao 2010-05-10 00:06:18

+0

@cHao:数组不通过引用传递。这就是为什么我使用'&'在第二个示例中通过引用显式传递'$ result'数组。 – 2010-05-10 00:10:56