如何将此循环限制为特定数字?

时间:2011-01-18 00:25:14

标签: php

如何限制此循环才能获得6个值?

  $countries = array();
foreach ($my_data as $node)
{   
    foreach($node->getElementsByTagName('a') as $href)
    {   

        $countries[] = strip_tags(trim($href->nodeValue)); 


    }
}

5 个答案:

答案 0 :(得分:2)

$i = 0;
foreach($node->getElementsByTagName('a') as $href)
{
    if ($i++ === 6) break;   
    $countries[] = strip_tags($href->nodeValue); 

}

答案 1 :(得分:2)

我相信getElementsByTagName()会返回一个数组。在这种情况下,您可以:

foreach(array_slice($node->getElementsByTagName('a'),0,6) as $href)
{   
    $countries[] = strip_tags($href->nodeValue); 

}

请参阅:http://us.php.net/manual/en/function.array-slice.php

答案 2 :(得分:1)

如果计数器达到6,则使用计数器计算值,然后使用break计算出循环:

$countryCount = 0
foreach($node->getElementsByTagName('a') as $href)
    {   
        $countries[] = strip_tags($href->nodeValue);
        $countryCount++
        if ($countryCount >= 6) break;
    }

答案 3 :(得分:1)

我就是这样做的......

$countries = array();

$countryCount = 0;
$countryLimit = 6;
foreach ($my_data as $node)
{   
    foreach($node->getElementsByTagName('a') as $href)
    {   

        $countries[] = strip_tags(trim($href->nodeValue)); 

if($countryCount == "$countryLimit")
{
break;
}

$countryCount++


    }
}

答案 4 :(得分:0)

我觉得这样更好:

$array = $node->getElementsByTagName('a');
for($counter = 0; $counter < min(count($array), 6); ++$counter) {
    $countries[] = strip_tags($array[$counter]->nodeValue); 
}

循环中的断裂是一种不好的做法,我会说。这种循环快速且易于阅读。

相关问题