Создание словосочетаний

Например, это мой текст:

$str = 'buy new microsoft windows';

Я взорву текст и список с массивом:

Array
(
    [0] => buy
    [1] => new
    [2] => microsoft
    [3] => windows
)

Я хочу генерировать слова в массиве примерно так:

buy new
buy new windows
buy microsoft 
buy microsoft windows
buy windows
new microsoft
new microsoft windows
new windows
microsoft windows

Я пробовал с foreach и rand, но я не мог сгенерировать, как показано. Есть ли возможность генерировать, как и мой запрос?

Ответ 1

Вы можете посмотреть этот PEAR PACKAGE Пример использования:

<?php
require_once 'Math/Combinatorics.php';
$words = array('buy', 'new', 'microsoft');
$combinatorics = new Math_Combinatorics;
foreach($combinatorics->permutations($words, 2) as $p) {
  echo join(' ', $p), "\n"; 
}

Выход будет:

buy new
new buy
buy microsoft
microsoft buy
new microsoft
microsoft new

Ответ 2

shuffle($array);
echo join(' ', array_slice($array, 0, mt_rand(1, count($array))));

Это дает вам одно случайное "предложение". При необходимости повторите.

Ответ 3

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        print join(' ', $perms) . "\n";
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            pc_permute($newitems, $newperms);
        }
    }
}

источник: http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm#phpckbk-CHP-4-EX-6

также проверьте следующий пример на этом сайте


пример: pc_permute( explode( ' ', 'buy new microsoft windows' ) );

buy new microsoft windows
new buy microsoft windows
buy microsoft new windows
microsoft buy new windows
new microsoft buy windows
microsoft new buy windows
buy new windows microsoft
new buy windows microsoft
buy windows new microsoft
windows buy new microsoft
new windows buy microsoft
windows new buy microsoft
buy microsoft windows new
microsoft buy windows new
buy windows microsoft new
windows buy microsoft new
microsoft windows buy new
windows microsoft buy new
new microsoft windows buy
microsoft new windows buy
new windows microsoft buy
windows new microsoft buy
microsoft windows new buy
windows microsoft new buy

Ответ 4

Найдено из php.net shuffle doc

function powerSet($in,$minLength = 1) { 
   $count = count($in); 
   $members = pow(2,$count); 
   $return = array(); 
   for ($i = 0; $i < $members; $i++) { 
      $b = sprintf("%0".$count."b",$i); 
      $out = array(); 
      for ($j = 0; $j < $count; $j++) { 
         if ($b{$j} == '1') $out[] = $in[$j]; 
      }
      $out_val = implode(" ", $out); 
      if (count($out) >= $minLength) { 
         $return[] = $out_val; 
      } 
   } 
   return $return; 
}

print_r(powerSet($str_arr));

и результаты будут,

Array
(
    [0] => windows
    [1] => microsoft
    [2] => microsoft windows
    [3] => new
    [4] => new windows
    [5] => new microsoft
    [6] => new microsoft windows
    [7] => buy
    [8] => buy windows
    [9] => buy microsoft
    [10] => buy microsoft windows
    [11] => buy new
    [12] => buy new windows
    [13] => buy new microsoft
    [14] => buy new microsoft windows
)

Ответ 5

Для всех возможных комбинаций я улучшил @SujitAgarwal Ответ:

Загрузите Math_Combinatoeics.

include_once 'Combinatorics.php';

$words = array('buy','microsoft','windows');
$count = count($words);
$return = array();

$combinatorics = new Math_Combinatorics;

for ($num=1; $num <= $count; $num++ ){
  foreach($combinatorics->permutations($words, $num) as $p) {
    $return[] = join(' ', $p);
  }
} 

print_r($return);

Выход:

Array
(
  [0] => buy
  [1] => microsoft
  [2] => windows
  [3] => buy microsoft
  [4] => microsoft buy
  [5] => buy windows
  [6] => windows buy
  [7] => microsoft windows
  [8] => windows microsoft
  [9] => buy microsoft windows
  [10] => buy windows microsoft
  [11] => microsoft windows buy
  [12] => microsoft buy windows
  [13] => windows buy microsoft
  [14] => windows microsoft buy
)