循环数组项并限制显示


Loop array items and limit the display

有一个名为array$banners,其中有几个数据值是从我的数据库中提取的。对于这个array,我只想显示其中的七个值。所以我:

$count = count($banners);
for($count; ; $count++) {
  if($count > 7) {
    break;
  }
  foreach ($banners as $banner) {
    echo "<div>Hey, this is a " . $banner "!</div>"
  }
}

仅当array包含的项目少于或等于7个时,才会显示该代码。否则,如果array的值超过7,则屏幕上将不会显示任何内容。

所以,不管代码有两项还是一千项。屏幕上只能打印七个!有没有办法为它调整循环?

使用min显示最大7元素,使用while循环和pop显示横幅:

$count = min(7, count($banners)); 
while ($count--) { 
    $banner = array_pop($banners); 
    echo "<div>Hey, this is a " . $banner ."!</div>"; 
} 
$count = 0;
$arraySize = count($banners);
foreach ($banners as $banner) {
    if($count++ < $arraySize)
        echo "<div>Hey, this is a " . $banner "!</div>"
    else break;
}

如果你这样做,无论怎样,循环都只会迭代7次:

$count = count($banners);
for($x = 0; $x < 7; $x++) {
    echo "<div>Hey, this is a " . $banner[$x] . "!</div>"
  }
}

$x是一个单独的变量,用于计算循环迭代次数,您可以使用它从数组中选择第n个元素。

在一个数组上限制为7次(或更少)迭代并显示结果非常容易(请参阅其他答案)。然而,显而易见的问题是:

为什么不从数据库中选择7个项目的限制?

我认为sizeof()函数就是您想要的。。

if(sizeof($banner)<=7) {

 foreach ($banners as $banner)
 {
    echo "<div>Hey, this is a " . $banner "!</div>"
 }

}

foreach ($banners as $key => $banner) 
{
  if($key == 7) 
  {
    break; //Breaking code flow!
  }
  echo "<div>Hey, this is a " . $banner "!</div>"
}