Heim  >  Fragen und Antworten  >  Hauptteil

PHP-getrennte Zufallszahl, nicht wiederholbar

Ich habe den folgenden PHP-Code, der beim Hinzufügen einer statischen Zahl ;100 Zufallszahlen erstellt und die Zahl durch | dividiert Es funktioniert einwandfrei, erzeugt aber doppelte Nummern. Wie kann ich verhindern, dass doppelte Nummern erstellt werden?

echo shd ist 3;100|2;100, aber vor ;100 gibt es keine wiederholte Zahl. Dieser Code gibt jedoch manchmal Zahlen wie 2;100|2;100 aus, die wiederholt werden.

<?php
$kat_list=array(1,2,3,4);

$count_cat= rand(2,3);

for ($i = 1; $i <= $count_cat; $i++) {
    $rnd_cat= rand(0,count($kat_list)-1);
    $kats[]=$kat_list[$rnd_cat].'--100';

}
$line=implode('-',$kats);

 $line=str_replace('--', ';', $line);
 $line=str_replace('-', '|', $line);
 


 echo $line;

P粉131455722P粉131455722382 Tage vor522

Antworte allen(2)Ich werde antworten

  • P粉512526720

    P粉5125267202023-09-07 14:36:59

    您可以在数组内爆之前使用 array_unique 删除重复项

    $kat_list=array(1,2,3,4);
    
    $count_cat= rand(2,3);
    
    for ($i = 1; $i <= $count_cat; $i++) {
        $rnd_cat= rand(0,(count($kat_list)-1));
        $kats[]=$kat_list[$rnd_cat].'--100';
    
    }
    
    $kats = array_unique($kats);
    
    $line=implode('-',$kats);
    
    $line=str_replace('--', ';', $line);
    $line=str_replace('-', '|', $line);
     
     echo $line;

    Antwort
    0
  • P粉807397973

    P粉8073979732023-09-07 11:50:21

    $kat_list=array(1,2,3,4);
    shuffle($kat_list); // shuffle list
    $count=3;
    for($i=0; $i<$count; ++$i) {
        // get the first N items of the shuffled list
        printf("%d ", $kat_list[$i]);
    }
    

    尝试一下:https://3v4l.org/a31pv

    Antwort
    0
  • StornierenAntwort