2013-04-09 1 views
1

개인 생성 도구로 키워드 생성 도구를 만들고 있습니다. 제공된 키워드 목록에서 가능한 모든 조합을 찾기 위해 다차원 배열을 반복하는 재귀 함수를 설정했습니다. 를 통해 성공적으로 반복다차원 배열 서식

$data = array(
    array('New York', 'New York City'), 
    array('hotel', 'lodging','motel'), 
); 

$results = recurseful('', $data); 

저에게 다양한 키워드 조합의 목록을 제공합니다

public function recurseful($start, $args) 
{ 
if (is_array($args)) 
    { 
     foreach ($args[0] as $value) 
     { 
      $this->output[] = trim("{$start} {$value}"); 
      if (count($args) > 1) 
      { 
       $this->recurseful($value, array_slice($args, 1)); 
      } 
     } 
    } 
return; 
} 

내가 전달하고있다. 그러나 모두 $ output의 단일 배열로 반환합니다. 이 함수는 $ Data [0] (또는 $ args [0])의 값을 가져 와서 주어진 다른 키워드와 비교하도록 설계되었습니다.

는 차라리 그들
1st ('New York', 'New York City') 
2nd ('New York hotel', 'New York lodging', 'New York motel') 
3rd ('New York City hotel', 'New York City lodging', 'New York City motel') 

그것은 현재 하나에 그 경기를 모두 반환

을 반환 것입니다. 어떻게하면 다른 배열로 갈 수 있습니까? 첫 번째은 정확히 일치하는 $data[0]입니다. 그럴 수는 있지만 $data[0]의 한 값에 대해 가능한 모든 조합을 반복 한 후 새 배열을 강제 적용하려면 어떻게해야합니까? (따라서 $data[0]에 3 개의 값이 있으면 3 개의 추가 배열이 반환됩니다.)

스크린 샷 사용자가 원하는 단어를 스프레드 시트에 입력 할 수 있습니다. Initial Input

결과는 다음과 유사하게 반환됩니다. 그래서 나는 그것의 자신의 배열에 데이터의 각 열을 넣고 싶습니다. Expected Output 위의 현재 솔루션은 모든 것을 자체 배열에 넣기 때문에 동일한 열에 다시 반환됩니다. 나는 이후 많은 작업 솔루션에 도착

var_dump

+0

예상되는 출력은 무엇입니까? – mariotanenbaum

+1

다차원 배열 ($ this-> output에 할당 됨)을 기대하고 있습니다. 그리고 위에서 설명한대로 서식을 지정할 것입니다. – EnigmaRM

+0

나는 원하는 출력을 이해할 수 있는지 100 % 확신하지 못하고 있지만 병합 중입니다. 전달하기 전에 $ data 배열을 사용하면 PHP 함수를 찾을 수 있습니다. [array_merge_recursive] (http://www.php.net/manual/en/function.array-merge-recursive.php) – mariotanenbaum

답변

0

더 많은 동료에서 & 도움을 생각했다.

function permutate($data, $limit){ 
    $this->limit = $limit; 
    $this->data = $data; 
    $this->numLevels = count($this->data); 

    $this->possiblePermutations = 1; 
    foreach ($this->data as $array){ 
     $this->possiblePermutations *= count($array); 
    } 
    for ($i = 0; $i < $this->numLevels - 0; $i++){ 
     $this->permutations[$i] = array(); 
    } 

    $this->recurse(0, 0, ''); 

    return $this->permutations; 
} 

private function recurse($currentLevel, $level, $string){ 
    if ($this->numPerms == $this->limit) 
     return; 

    foreach ($this->data[$level] as $val){ 
     if ($this->numPerms == $this->limit) 
      return; 

     $newString = "$string $val"; 
     if ($level == $currentLevel){ 
      $this->permutations[$level][] = trim($newString); 
      $this->numPerms++; 
     } 

     if ($level < $this->numLevels - 1 AND $level <= $currentLevel){ 
      $this->recurse($currentLevel, $level + 1, $newString); 
     } 
    } 

    if (! $level AND $currentLevel < $this->numLevels){ 
     $this->recurse($currentLevel + 1, 0, ''); 
    } 
} 

이렇게하면 원하는 결과를 얻을 수 있습니다.