Limiting output within a foreach loop

2019-08-04 06:06发布

问题:

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