我的問題可能很容易回答。但我無法弄清楚。我怎樣才能生成多個隨機數字在沒有相同的PHP
<?php
$id1 = rand(1,4);
$id2 = rand(1,4);
$id3 = rand(1,4);
$id4 = rand(1,4);
?>
我有這個。但是這有時會創建多個3等。但在我的項目中,這是不可能發生的事情。最後,範圍將在1到100之間。但這只是爲了測試它如何工作。有人可以幫幫我嗎?
我的問題可能很容易回答。但我無法弄清楚。我怎樣才能生成多個隨機數字在沒有相同的PHP
<?php
$id1 = rand(1,4);
$id2 = rand(1,4);
$id3 = rand(1,4);
$id4 = rand(1,4);
?>
我有這個。但是這有時會創建多個3等。但在我的項目中,這是不可能發生的事情。最後,範圍將在1到100之間。但這只是爲了測試它如何工作。有人可以幫幫我嗎?
創建您可以從中選擇的一系列值。 隨機播放並獲取前N個結果。
$range = range(0, 100);
shuffle($range);
$n = 10;
$result = array_slice($range, 0 , $n);
這是什麼目的?
但是,也許你可以簡單地這樣做:
$ids = range(1, 10);
shuffle($ids);
var_dump($ids);
/*
* 1st Result:
*
* array (size=10)
* 0 => int 10
* 1 => int 2
* 2 => int 5
* 3 => int 7
* 4 => int 9
* 5 => int 1
* 6 => int 3
* 7 => int 6
* 8 => int 4
* 9 => int 8
*/
var_dump($ids);
/*
* 2nd Result:
*
* array (size=10)
* 0 => int 5
* 1 => int 9
* 2 => int 6
* 3 => int 4
* 4 => int 2
* 5 => int 10
* 6 => int 3
* 7 => int 7
* 8 => int 8
* 9 => int 1
*
*/
檢查這個代碼:
$values=array(); #preparint storage for numbers
$found=0; #number of found numbers
while($found!=4): #script is looking for 4 numbers
$v=rand(1,4); #range of numbers (1-4)
if(!in_array($v,$values)): #if found number isn't in array
$values[]=$v; #add it
$found++; #and increment counter
endif;
endwhile;
foreach($values as $value):
echo '<p>'.$value.'</p>'; #echo found numbers
endforeach;
腳本準備在1-4範圍內找到4個隨機,唯一的編號。
$temp = array() // global
$id1 = is_num_exists(rand(1,4));
$id2 = is_num_exists(rand(1,4));
$id3 = is_num_exists(rand(1,4));
$id4 = is_num_exists(rand(1,4));
function is_num_exists($id){
while(in_array($id,$temp)){
$id = rand(1,4);
}
$temp[] = $id;
return $id
}
有實現這一幾種方法:
創建給定的範圍(使用range()
功能)的陣列,並且將它洗。要檢索這些值,你可以走它。如果你的範圍不是太大,這很有用。這似乎是你的情況。
$range = range(1, 10);
shuffle($range);
如果您的範圍要大得多,你最好存儲你選擇的值到排序後的數組,檢查被存在所述陣列內的每個後續的隨機數。這隻適用於非常大的範圍,因爲不像第一個例子那樣,所有可能的值都被加載到內存中。
$passedValues = array();
for ($i = 0; $i < 10; $i++) {
$v;
do {
$v = rand(1, 100);
}
while (in_array($passedValues));
$passedValues[] = $v;
sort($passedValues);
}
其他的答案提供了一些偉大的代碼示例。
如果數字不是太多,請嘗試將它們存儲到一個數組,並過濾掉重複的數字。 –
從1-4創建一個數組,然後對數組進行隨機排序。 – David
如果您生成4個隨機數,甚至有可能它們都是相同的。與你的短距離,這種可能性更高。最後你想要什麼?數字1-4以隨機順序排列,還是有限數量的重複? – Desaroll