Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

php - How to apply a class randomly without to duplicate in loop?

I have a loop where I am inserting some html element and I need to add a class to it but I need this class to be from 1 to 4 max, like gallery__item--3 or gallery__item--1 and applied randomly without duplicates and avoid gallery__item--3 and gallery__item--3.

Currently I do the following but I get duplicates and I am not sure how to check:

$min = 1;
$max = 4;
foreach( $galleria as $image ):  
  <figure class="gallery__item--<?php echo rand($min,$max); ?>">
endforeach;

Literally looking for:

1,3,4,2 or 4,2,1,3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you want to avoid duplicates, I assume there are only four images.

You can use shuffle to randomize a previously created array:

$rands = range(1,4);
shuffle($rands);
foreach( $galleria as $image ):  
  <figure class="gallery__item--<?= array_pop($rands); ?>">
endforeach;

If you have more than 4 elements you can still use this approach checking if there are elements left and regenerating the array. If you need every iteration to be different you can also check that the ordering hasn't been used before (just keep in mind that there are a limited number of combinations).

$rands = [];
$pasts = [];

foreach( $galleria as $image ):  
    if (empty($rands)):
        do {
            $rands = range(1,4);
            shuffle($rands);
        } while (in_array($rands, $pasts)); 
        $pasts[] = $rands;
    endif;
    <figure class="gallery__item--<?= array_pop($rands); ?>">
endforeach;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...