我有一个下面有单词的数组作为例子。
$words = array('hello','world','wad','up','yo','etc');
我想要的是下一个数组,以下操作上面的
$phrase2 = array('hello world', 'world wad', 'wad up', 'up yo', 'yo etc');
$phrase3 = array('hello world wad', 'world wad up', 'wad up yo', 'up yo etc');
$phrase4 = array('hello world wad up', 'world wad up yo', 'wad up yo etc');
$phrase5 = array('hello world wad up yo', 'world wad up yo etc');
我希望我的问题很明确。
答案 0 :(得分:3)
而不是$ phrase2,$ phrase3,...我的代码使用$ phrase [2],$ phrase [3],...
但是如果你想使用$ phrase2,$ phrase3,$ phrase4,那么只需将以下代码添加到我的末尾:
$phrase2 = $phrase[2];
$phrase3 = $phrase[3];
$phrase4 = $phrase[4];
$phrase5 = $phrase[5];
这是我的代码,只是试一试!:
<?php
$words = array('hello','world','wad','up','yo','etc');
$phrase = array();
for($i=2; $i<=count($words); $i++)
{
foreach($words as $key => $value)
{
if($key <= count($words)-$i)
{
$phrase_value[] = $value;
for($j=1; $j<$i; $j++)
{
$phrase_value[] = $words[$key+$j];
}
$phrase[$i][] = implode(' ', $phrase_value);
unset($phrase_value);
}
}
}
// this deletes the last array in phrase
array_pop($phrase);
?>
输出如下:
Array
(
[2] => Array
(
[0] => hello world
[1] => world wad
[2] => wad up
[3] => up yo
[4] => yo etc
)
[3] => Array
(
[0] => hello world wad
[1] => world wad up
[2] => wad up yo
[3] => up yo etc
)
[4] => Array
(
[0] => hello world wad up
[1] => world wad up yo
[2] => wad up yo etc
)
[5] => Array
(
[0] => hello world wad up yo
[1] => world wad up yo etc
)
[6] => Array
(
[0] => hello world wad up yo etc
)
)
答案 1 :(得分:2)
切片数组然后破坏结果:
$words = array('hello','world','wad','up','yo','etc');
$phrase2 = array();
$phrase3 = array();
$phrase4 = array();
$lim = sizeof($words);
for($i=0;$i<$lim;$i++)
{
if($i < $lim - 1)
$phrase2[] = implode(" ",array_slice($words,$i,2));
if($i < $lim - 2)
$phrase3[] = implode(" ",array_slice($words,$i,3));
if($i < $lim - 3)
$phrase4[] = implode(" ",array_slice($words,$i,4));
}
答案 2 :(得分:1)
我尝试过这个编程练习。
<?php
$src1 = "hello world wad up yo etc";
$words = explode(" ",$src1);
$length = count($words);
print_r($words);
$phrases = array();
foreach( range(2,5) as $span ){
$shifter = create_function("\$n","{ global \$words; return join(\" \", array_slice(\$words,\$n,$span) ); }");
$sp = array_map( $shifter, range( 0, $length - $span ) );
###var_dump($sp);
$phrases["phrase$span"] = $sp;
}
print_r($phrases);