2017-05-31 37 views
-1

我有一個顯然很容易的任務,但我卡住了。我嘗試了重構和迭代器,但沒有想法打擊我。他們說,一張圖片的勝過千言萬語,所以我會告訴我的「圖像」例如數組:如何使用PHP中每個子數組中的一個值生成所有可能的組合?

array (size=4) 
    0 => 
    array (size=4) 
     0 => int 1 
     1 => int 2 
     2 => int 3 
     3 => int 4 
    1 => 
    array (size=3) 
     0 => string 'a' (length=1) 
     1 => string 'b' (length=1) 
     2 => string 'c' (length=1) 
    2 => 
    array (size=3) 
     0 => string 'X' (length=1) 
     1 => string 'Y' (length=1) 
     2 => string 'Z' (length=1) 
    3 => 
    array (size=5) 
     0 => string '!' (length=1) 
     1 => string '"' (length=1) 
     2 => string '#' (length=1) 
     3 => string '$' (length=1) 
     4 => string '%' (length=1) 

規則:

  1. 數組大小和子陣列尺寸是隨機的,而且相當巨大。
  2. 只能使用任何子數組中的一個值。
  3. 結果應從最短的字符串到最長的字符串排序。
  4. 由於生成了大量數據,因此必須提高內存效率,結果應該離線存儲/比較,如文件或MySQL數據庫。但每次都是。

所需的字符串組合的一個例子:

1 
2 
3 
4 
a 
b 
c 
X ... 
1a 
1b 
1c 
2a 
2b ... 
aX! 
aX" ... 
1aX! 
1aX" ....... 
4cZ% 

我嘗試了幾種迭代器等How to generate in PHP all combinations of items in multiple arrays

+0

因此,每行的長度介於1和數組中元素的數量?你想要所有可能的組合,還是隻有幾個,比如100? –

+0

所有組合,數組大小都是隨機的,在一個元素中最多可以有15000行,在一個數組中最多可以有50個元素。 – Ionut

+0

這裏似乎沒有關於這個問題的簡潔陳述。你能在第一段中總結一下嗎? – halfer

回答

0

在我的情況下,解決方案是這個遞歸函數,我切換了$combine變量,首先從數組插入單個值,然後將聯合設置爲true,合併數據庫中的所有值(除了包含當前迭代的值值):

  function iterdb($arrays, $i = 0, $combine = false) { 
       if (! isset(array_keys($arrays)[ $i ])) { 
        return false; 
       } 
       if ($i == 0 && $combine === true) { 
        //Adding empty option to obtain all combos 
        for ($x = 0; $x < count($arrays); $x ++) { 
         $arrays[ $x ][] = preg_replace('`=[^\&]+`', '=', $arrays[ $x ][0]); 
        } 
       } 

       $this->iterdb($arrays, $i + 1, $combine);//Call iteration on each following array 
       $transactions = array(); 
       sort($arrays[ $i ]); 
       $this->log('Iterating array ' . $i . ' using combine ' . ($combine ? 'True' : 'False')); 
       foreach ($arrays[ array_keys($arrays)[ $i ] ] as $v) { 
        if ($this->counter > 0) { 
         if ($combine === false) { 
          $transactions[] = "INSERT IGNORE INTO scout_queries (scout,query) VALUES ('" . $this->Class . "','$v')"; 
         } else { 
          $tmp = $this->queries->find(array(
           'scout = :scout and query NOT LIKE :query', 
           ':scout' => $this->Class, 
           ':query' => '%' . (array_values(explode('=', $v))[0]) . '%' 
          ), array('order' => 'CHAR_LENGTH(query) DESC')); 

          foreach ($tmp as $t) { 
           $transactions[] = "INSERT IGNORE INTO scout_queries (scout,query) VALUES ('" . $this->Class . "','" . $t->query . "&$v')"; 
           $transactions = $this->saveTransactions($transactions); 
          } 
         } 

        } 
        $transactions = $this->saveTransactions($transactions, true); 
       } 


       if ($i == 0 && $combine === false) { 
        return $this->iterdb($arrays, 0, true); 
       } 
      } 
相關問題