2013-04-09 72 views
1

我正在开发一个个人项目来创建关键字生成工具。 我已经设置了一个循环遍历多维数组的递归函数来找出提供的关键字列表中的所有可能的组合。多维数组格式化

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

我传递:

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

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

它通过迭代成功,并给了我不同的关键字组合的列表。但是,它将全部返回到$ 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 2013-04-09 06:19:20

+1

我期待一个多维数组(被分配到$ this-> output然后对他们进行如上所述的格式化 – EnigmaRM 2013-04-09 16:46:24

+0

我不是100%确定我明白你想要什么输出,而是合并$数据数组通过它们之前可以帮助。寻找PHP函数[array_merge_recursive](http://www.php.net/manual/en/function.array-merge-recursive.php) – mariotanenbaum 2013-04-09 06:18:06

回答

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

这给了我想要的结果。