这是我在这个网站上的第一个问题,所以我希望我对此足够具体。
我需要将一个文本字符串转换为多个数组,其中包含文本字符串中"单词"answers"单词短语"的所有不同组合。
所以字符串应该是:"2013年法国足球赛"
从这里我想要以下阵列:
array(
0 => array(
'Football',
'match',
'France',
'2013'
),
1 => array(
'Football',
'match',
'France 2013'
),
2 => array(
'Football',
'match France',
'2013'
),
3 => array(
'Football',
'match France 2013'
),
4 => array(
'Football match',
'France',
'2013'
),
5 => array(
'Football match',
'France 2013',
),
6 => array(
'Football match France',
'2013'
),
7 => array(
'Football match France 2013',
),
)
因此,每个结果字符串可以由1到n个连续单词组成,并且每个子数组总共应该包含一次每个单词的限制。
以下是一些有效的代码。
<?php
$str = 'Football match France 2013'; // Initialize sentence
$words = explode(" ",$str); // Break sentence into words
$p = array(array(array_shift($words))); // Load first word into permutation that has nothing to connect to
foreach($words as $word) { // for each remaining word
$a = $p; // copy existing permutation for not-connected set
$b = $p; // copy existing permutation for connected set
$s = count($p); // cache number of items in permutation
$p = array(); // reset permutation (attempt to force garbage collection before adding words)
for($i=0;$i<$s;$i++) { // loop through each item
$a[$i][] = $word; // add word (not-connected)
$b[$i][count($b[$i])-1] .= " ".$word; // add word (connected)
}
$p = array_merge($a,$b); // create permutation result by joining connected and not-connected sets
}
// Dump the array
print_r($p);
?>