我的学校任务有些问题。由于经验不足,我对操作数组感到困惑。我使用foreach
从数组中获取值,然后我希望在某些条件下得出结果:
$total_words
foreach
中有条件。 如果 $total words
未传递数组值中的字数,则打印所有数组值。但要其他打破所有字词然后按最后一个字数停止。有关详细信息,您可以看到我想要的结果
$array = array(
"There are many ways to get to Windows 10 Advanced Startup Options.",
"On many laptops, hitting F11 as soon as you power on will get you there.",
"Booting off an install disk and hitting Next then Repair will do the job",
"n ....................."
);
$total_words = 4;
foreach($array as $value){
$count = explode(" ", $value);
if( count($count) <= $total_words){
echo $value. "\n\n";
} else {
//echo i do something
break;
}
}
//output $total_words = 4;
/* There are many */
//output $total_words = 12;
/* There are many ways to get to Windows 10 Advanced Startup Options. */
//output $total_words = 16;
/* There are many ways to get to Windows 10 Advanced Startup Options. */
/* On many laptops, hitting */
//output $total_words = 20000;
/* There are many ways to get to Windows 10 Advanced Startup Options. */
/* On many laptops, hitting F11 as soon as you power on will get you there. */
/* Booting off an install disk and hitting Next then Repair will do the job */
/* n ..................... */
答案 0 :(得分:0)
这是我将使用的方法 - 假设我理解了这个问题。检查每次迭代时的单词计数,并根据需要截断文本或减少单词容差。
代码:(演示:https://3v4l.org/JFYsd)
function word_limiter($sentences,$word_allowance){
$text='';
foreach($sentences as $sentence){
$words=explode(' ',$sentence);
$word_count=count($words);
if($word_count>$word_allowance){
$text.=implode(' ',array_slice($words,0,$word_allowance));
// do something
break;
}elseif($word_count==$word_allowance){
$text.=$sentence;
break;
}else{
$text.="$sentence\n";
$word_allowance-=$word_count; // reduce allowance for next iteration
}
}
return $text;
}
$array = array(
"There are many ways to get to Windows 10 Advanced Startup Options.",
"On many laptops, hitting F11 as soon as you power on will get you there.",
"Booting off an install disk and hitting Next then Repair will do the job",
"n ....................."
);
echo word_limiter($array,4),"\n\n";
echo word_limiter($array,12),"\n\n";
echo word_limiter($array,16),"\n\n";
echo word_limiter($array,27),"\n\n";
输出:
There are many ways
There are many ways to get to Windows 10 Advanced Startup Options.
There are many ways to get to Windows 10 Advanced Startup Options.
On many laptops, hitting
There are many ways to get to Windows 10 Advanced Startup Options.
On many laptops, hitting F11 as soon as you power on will get you there.