Limiting output within a foreach loop

三世轮回 提交于 2019-12-11 08:52:14

问题


I have a multidimensional array, called $alternative, which contains words.

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.

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?

Thanks guys.


回答1:


$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;
        }
    }
}



回答2:


you may put counter inside like :

$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 == 9 ) {
            break;
            }else{
               counter++;
            }
            }

        }



回答3:


Simple. Implement a counter. The below implementation will spit out 10 <li> words for every set of alternative objects.

foreach ($alternative as $test)
{
    $count = 0;
    foreach ($test as $test2)
    {
        if ($count >= 10) break;
        $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);
        $count++;
    }

}

For just 10 <li> elements total, look at the other answer!




回答4:


You could simply use a counter and increment it each time you print a word. Here's a quick example:

$max_words = 10;
$nb_words = 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);
        $nb_words++;

        if($nb_words >= $max_words)
            break;
    }
    if($nb_words >= $max_words)
        break;
}


来源:https://stackoverflow.com/questions/17843762/limiting-output-within-a-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!