-2 php arrays string combinations
这是我在这个网站上的第一个问题,所以我希望我能够具体到此.
我需要将文本字符串转换为几个数组,其中包含文本字符串中"单词"和"单词短语"的所有不同组合.
所以字符串就像:"足球比赛法国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',
),
Run Code Online (Sandbox Code Playgroud)
)
因此限制每个结果字符串字符串可以包含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);
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
621 次 |
| 最近记录: |