>我有一个如下所示的字符串
$string = "hi hello how are you ? hope you";
我需要如下所示的数组结果
hi hello how
hello how are
how are you
are you hope
you hope you.
我尝试了如下所示的内容
$exp = explode(" ",$string);
foreach($exp as $lol)
{
//now i have no idea what to do..some 1 guide me please.
}
试试这个,使用array_shift
并运行循环两次。
注意:阅读答案中的评论,因为我在那里解释为什么我这样写。
<?php
$string = "hi hello how are you hope you";
$exp = explode(" ",$string);
for ($i=0; $i<(count($exp)+3);$i++)//as you want to print three value in
//each loop your loop should run three more time than
//the number of element you got in your original array
{
echo '<br/>';
for($k=0;$k<3;$k++)
{
echo ' ';//added the space to see
print_r($exp[$k]);//to see the result
}
$value= array_shift($exp);//after printing the result remove the
//first element from the array. so this will remove the first elemenet after
//each result.
}
您的结果将如下所示
hi hello how
hello how are
how are you
are you hope
you hope you
此代码示例给出了 2 个级别。没有的 foreach 就是 no 的文字。
$vari = "hai hello how?";
$vari = str_replace("?", "", $vari);
$vars = explode(" ", $vari);
$varp = $vars;
foreach ($vars as $p_i=>$p_v){
foreach($varp as $c_i=>$c_v){
if($p_i!=$c_i){
echo $p_v." ".$c_v."<br/>";
}
}
}
结果
hai hello
hai how
hello hai
hello how
how hai
how hello
您可以将foreach放入另一个foreach中以获取更多单词。