PHP设置要显示的最大图像计数

PHP设置要显示的最大图像计数,php,Php,我有一个从文件夹中提取图像并在网站上显示的代码。问题是我只想显示最多12个图像(随机)。由于我不熟悉PHP,我希望有人能在这里提供帮助 我的密码是: <?php foreach($this->images as $image) { $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;

我有一个从文件夹中提取图像并在网站上显示的代码。问题是我只想显示最多12个图像(随机)。由于我不熟悉PHP,我希望有人能在这里提供帮助

我的密码是:

<?php
    foreach($this->images as $image)
    {
        $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;
        echo '<img src="'.$path.$image->fname.$image->type.'" alt="'.$this->p->street_address.'" width="320" style="margin: 10px 5px 0px 5px;"/> ';
    }
?>


或者甚至更早,根据您设置$this->images的方式,您可能可以将其减少为仅包含12个条目的数组。有很多方法可以做到这一点,您必须限制foreach循环,实现它的一种方法如下。
<?php
    $count= 0;
    foreach($this->images as $image)
    {
        if($count > 12)
                break;

        $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;
        echo '<img src="'.$path.$image->fname.$image->type.'" alt="'.$this->p->street_address.'" width="320" style="margin: 10px 5px 0px 5px;"/> ';
        $count++;
    }
?>
在下面的代码中,我把$i=0
so count从零开始,然后在foreach循环中,我在i上加上增量,如果条件成功
if(++$i==11)break,则加上限制并中断代码

<?php
    $i = 0;
  foreach($this->images as $image)
  {
   if (++$i == 11) break;
   $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;
    echo '<img src="'.$path.$image->fname.$image->type.'" alt="'.$this->p->street_address.'" width="320" style="margin: 10px 5px 0px 5px;"/> ';

   }
?>

如果要显示图像数组中的12个随机图像,可以尝试以下操作:

if(count($this->images) > 12) {
    $randomKeys = array_rand($this->images, 12);
} else {
    $randomKeys = array_rand($this->images, count($this->images));
}
foreach($randomKeys as $key) {
    $image = $this->images[$key];
    $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;
    echo '<img src="'.$path.$image->fname.$image->type.'" alt="'.$this->p->street_address.'" width="320" style="margin: 10px 5px 0px 5px;"/> ';
}
if(计数($this->images)>12){
$randomKeys=array\u rand($this->images,12);
}否则{
$randomKeys=array_rand($this->images,count($this->images));
}
foreach($key作为$key){
$image=$this->images[$key];
$path=($image->remote==1)?$image->path:$this->ipbaseurl.$this->settings->imgpath;
回显“fname.$image->type.”“alt=“”。$this->p->street_address.”“width=“320”style=“margin:10px 5px 0px 5px;”“/>”;
}

从数组中选择12个随机键,然后循环遍历这些键。如果图像数组中的项目少于12个,则以随机顺序使用数组中的所有项目。

图像是全部或随机重新添加的?非常感谢大家的帮助-这是一个非常好的社区-非常有效!请注意,这不会以随机顺序打印图像订单。
if(count($this->images) > 12) {
    $randomKeys = array_rand($this->images, 12);
} else {
    $randomKeys = array_rand($this->images, count($this->images));
}
foreach($randomKeys as $key) {
    $image = $this->images[$key];
    $path = ($image->remote == 1) ? $image->path : $this->ipbaseurl.$this->settings->imgpath;
    echo '<img src="'.$path.$image->fname.$image->type.'" alt="'.$this->p->street_address.'" width="320" style="margin: 10px 5px 0px 5px;"/> ';
}