简体   繁体   English

循环数组项并限制显示

[英]Loop array items and limit the display

There is an array named $banners with several data values pulled from my database. 有一个名为$bannersarray具有从我的数据库中提取的几个数据值。 For this array , I'd like to display only seven of these values. 对于此array ,我只想显示其中七个值。 So I: 所以我:

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

The code will display only if the array contains less or equal than 7 items. 仅当array包含少于或等于7个项目时,才会显示代码。 Otherwise, if array has more than 7, nothing will appear in the screen. 否则,如果array大于7,则屏幕上将不会显示任何内容。

So, no matter if the code has two or thousand items. 因此,无论代码是否包含两千个项目。 Only seven should be printed on the screen! 屏幕上只能打印七个! Is there anyway to adjust the loop for it? 无论如何,有没有为此调整循环?

use min to display max 7 element, use a while loop and pop a banner to display: 使用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;
}

If you do it this way, the loop will only iterate 7 times no matter what: 如果以这种方式执行此操作,则无论哪种情况,循环都只会迭代7次:

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

The $x is a separate variable for counting the loop iterations, and you can use it to select the nth element from your array. $ x是一个用于计算循环迭代次数的单独变量,您可以使用它从数组中选择第n个元素。

It's quite easy to limit to 7 (or less) iterations on an array and display the results (see other answers). 将一个数组限制为7次(或更少)迭代并显示结果是很容易的(请参阅其他答案)。 However the glaring question is: 但是,明显的问题是:

Why aren't you selecting a limit of 7 items from your database? 为什么不从数据库中选择7个项目的限制?

I think sizeof() function is what you are looking for.. 我认为sizeof()函数就是您要寻找的..

if(sizeof($banners) <= 7) { if(sizeof($ banners)<= 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>"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM