php中洗牌项目的最大数量

php中洗牌项目的最大数量,php,Php,假设我有30张图片。 和3个尺寸,“小”、“中”、“大” 我想以随机顺序输出所有30幅图像,并给出一个随机大小的类,小/中和大 现在是这样的 $random = array("small", "medium", "large"); $images_array = *ALL IMAGES HERE* shuffle($images_array); foreach($images_array as $image){ ?> <div class="box <?php ech

假设我有30张图片。 和3个尺寸,“小”、“中”、“大”

我想以随机顺序输出所有30幅图像,并给出一个随机大小的类,小/中和大

现在是这样的

$random = array("small", "medium", "large");
$images_array = *ALL IMAGES HERE*
shuffle($images_array);

foreach($images_array as $image){ ?>
    <div class="box <?php echo $random[rand(0, count($random) - 1)]; ?>"><img src="<?php echo $image; ?>" /></div>
<?php } ?>
$random=数组(“小”、“中”、“大”);
$images\u array=*此处的所有图像*
洗牌($images\u数组);
foreach($images\u数组作为$image){?>

您只需使用
$计数器
变量来计算
大的
值被使用的次数。如果超过,只需再次随机化该值

<?php
$random = array("small", "medium", "large");
$images_array = *ALL IMAGES HERE*
shuffle($images_array);

$counter = 0;
foreach($images_array as $image){ ?>
    $rand = rand(0, $counter > 3 ? 1 : 2);
    if ($rand == 2) $counter++;  // corresponds to `large`
    echo '<div class="box ' . $random[$rand] .'"><img src="'. $image .'" / </div>';
}

$rand=rand(0,$counter>3?1:2);
如果($rand==2)$counter++;//对应于“大”`
回声';
}

只需创建一个包含30个值的数组,其中4个值为
“大”
,其余值为
“小”
“中”
的随机组合。此数组在洗牌时将获得所需的结果

<?php
$random = array("large", "large", "large", "large");
for ($i = 0; $i < 26; $i++) {
    $random[] = (rand(1, 2) == 1) ? "small" : "medium";
}
$images_array = *ALL IMAGES HERE*
shuffle($random);
shuffle($images_array);

foreach ($images_array as $key => $image) {
    echo '<div class="box '.$random[$key].'"><img src="'.$image.'" /></div>';
}
?>



foreach
循环中的第一行应更改为
$rand=($counter<4)?兰德(0,2):兰德(0,1)然后应删除第三行。我认为这会提高代码的效率。太棒了,谢谢!如果我有一个无限的图像数组呢?编辑,抱歉,只需删除for循环=)
<?php $large = 0;
foreach($images_array as $image){
  $class = $random[rand(0, count($random) - 1)];
  if ($class == 'large') {
    $large++;
    if ($large > 4)
     $class = $random[rand(0, count($random) - 2)];
  }
  echo '<div class="box ' . $class .'"><img src="' . $image . '" /></div>';
} ?>