我想获得一个句子中所有可能的短语(实际上存在)
$str = 'word1 word2 word3 word4';
$output = array ('word1 word2 word3', 'word1 word2',
'word2 word3 word4', 'word3 word4', 'word2 word3');
为此,我创建了一个单词数组,
$words = explode(' ', $str);
这里有几个问题可以解释如何构建数组元素的所有组合,但是如何在保留原始顺序的同时进行所有组合?
如何从$output
中制作$words
的数组?
答案 0 :(得分:1)
array_slice()
函数从输入数组中取出一个块。它还将确保顺序保持不变,并且组合是连续值的组合(按照原始数组)。$offset
和$length
用于块。$offset
值将基本上从头到尾循环; $length
最初将从偏移量开始计算剩余值,然后递减至2(我们不希望将单个值作为组合)。尝试以下操作( Rextester DEMO ):
$str = 'word1 word2 word3 word4';
$words = explode(' ', $str);
$combinations = array();
// offset from start to end of the words
for($offset = 0; $offset < count($words); $offset++) {
// length from available remaining words to 2
for ($length = count($words) - $offset; $length > 1; $length--) {
// get the array chunk
$combinations[] = array_slice($words, $offset, $length);
}
}
// test output
print_r($combinations);
输出:
Array
(
[0] => Array
(
[0] => word1
[1] => word2
[2] => word3
[3] => word4
)
[1] => Array
(
[0] => word1
[1] => word2
[2] => word3
)
[2] => Array
(
[0] => word1
[1] => word2
)
[3] => Array
(
[0] => word2
[1] => word3
[2] => word4
)
[4] => Array
(
[0] => word2
[1] => word3
)
[5] => Array
(
[0] => word3
[1] => word4
)
)