在foreach循环中限制输出 [英] Limiting output within a foreach loop
本文介绍了在foreach循环中限制输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多维数组,称为 $ alternative
,其中包含单词。
I have a multidimensional array, called $alternative
, which contains words.
此数组是动态生成的,有时可能只有3个字,而有时可能只有300个字。
This array is dynamically generated, sometimes there may only be 3 words, other times there could be 300 words.
在下面的代码中,我将单词从数组输出到网页。
In the below code, I am outputting the words from the array to the webpage.
如何将输出限制为只能说10个字?
How could I limit the output to say, 10 words?
foreach ($alternative as $test)
{
foreach ($test as $test2)
{
$test3 = ucwords($test2); //Capitalizes first letter of each word
printf('<li><a href="related.php?query=%1$s" title="%1$s" >%1$s</a></li>', $test3);
}
}
此刻,在某些情况下,显示的单词过多,我想将其限制为十个单词。
At the moment, on certain occasions, too many words are being displayed, and I would like to limit it to ten words.
我想不出一种方法。有人有什么建议吗?
I cannot think of a way to do this. Does anybody have any suggestions?
谢谢大家。
推荐答案
$counter = 0;
foreach ($alternative as $test) {
foreach ($test as $test2) {
$test3 = ucwords($test2); //Capitalizes first letter of each word
printf('<li><a href="related.php?query=%1$s" title="%1$s" >%1$s</a></li>', $test3);
if (++$counter > 10) {
break 2;
}
}
}
这篇关于在foreach循环中限制输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文