arrays - Create every possible combination in PHP -


so, trying list of every possible combination of set of words.

with input text "1, 2" , values being ("1" => "a", "b", "c") , ("2" => "d", "e"), like:

a, d b, d c, d a, e b, e c, e 

with code have right now, get:

a, d b, d c, d 

how can around this?

code:

foreach ($words $word) {     ($i = 0; $i < count($array); $i++) //for every value     {         $key = array_keys($array[$i])[0];         if ($word === $key)         {             $syn = explode("|", $array[$i][$key]); //get synonyms             foreach ($syn $s) //for each synonym within             {                  $potential[] = implode(" ", str_replace($key, $s, $words));             }         }     } } 

the procedure every word in input text, want go through our entire array of values. in there, have other arrays ("original" => "synonyms"). there, loop through every synonym , add list of potential combinations.

there few steps involved:

  1. narrow down list of synonyms found in string
  2. create template build final sentences
  3. get synonym combinations , apply them template

the following that:

$dict = [     '1' => ['a', 'b', 'c'],     '2' => ['d', 'e'], ];  $str = '2, 1';  class sentencetemplate implements iteratoraggregate {     private $template;     private $thesaurus;      public function __construct($str, $dict)     {         $this->thesaurus = [];          $this->template = preg_replace_callback('/\w+/', function($matches) use ($dict) {             $word = $matches[0];             if (isset($dict[$word])) {                 $this->thesaurus[] = $dict[$word];                 return '%s';             } else {                 return $word;             }         }, $str);     }      public function getiterator()     {         return new arrayiterator(array_map(function($args) {             return vsprintf($this->template, $args);         }, $this->combinations($this->thesaurus)));     }      private function combinations($arrays, $i = 0) {         if (!isset($arrays[$i])) {             return array();         }         if ($i == count($arrays) - 1) {             return $arrays[$i];         }          // combinations subsequent arrays         $tmp = $this->combinations($arrays, $i + 1);          $result = array();          // concat each array tmp each element $arrays[$i]         foreach ($arrays[$i] $v) {             foreach ($tmp $t) {                 $result[] = is_array($t) ? array_merge(array($v), $t) : array($v, $t);             }         }          return $result;     } }  $sentences = new sentencetemplate($str, $dict); foreach ($sentences $sentence) {     echo "$sentence\n"; } 

demo


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -