2010-05-09 6 views
5

나는이 배열을2 차원 배열의 모든 가능성

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

: 다음

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

:

답변

4

이 같은 재귀 함수를 만들 수 있습니다 like :

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에서 어떻게 깨지지 않습니까? 내 말은, 그것은 작동하지만 ... 왜? 나는 배열과 객체에 대해 항상 읽고있는 것을 기억하고 있다고 생각했다. $ array가 엉망이되어 버리지는 않을까? – cHao

+0

@cHao : 배열은 참조로 전달되지 않습니다. 그래서 두 번째 예제에서 '$ result' 배열을 참조로 명시 적으로 전달하기 위해'&'를 사용합니다. –

관련 문제