這裏我的我的用於產生三個詞的組合(combo_generator.php)代碼:如何防止重複組合兩個隨機數字?
<?php
include "db_connect.php";
// Query database of words
$words_sql = "SELECT * FROM words";
$words_res = mysqli_query($db, $words_sql)or die(mysqli_error());
// Create array of words
$array = array();
// Loop through each word and add each to the array
while($row = mysqli_fetch_array($words_res)){
$array[] = $row['word'];
}
// Set $word1 as random word from $array
$ran_num = array_rand($array);
$word1 = $array[$ran_num];
// Remove the chosen word from the array
array_splice($array, $ran_num, 1);
// Reset the array
$array2 = $array;
// Set $word2 as random word from $array
$ran_num2 = array_rand($array2);
$word2 = $array2[$ran_num2];
// Set variables
$word = 'star';
$three_words = "$word.$word1.$word2";
echo $three_words;
?>
這是我的用於分配隨機三字組合從數據庫(test.php的)每個星號代碼:
<?php
include "db_connect.php";
// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());
// Loop through every star in the array
while($row = mysqli_fetch_array($stars_res)){
// Store the star name in a variable
$star = $row['star_name'];
// Create a random 3-word combination
include "combo_generator.php";
// Attach the random 3-word combination to the star
echo $star.' '.$three_words.'<br/><br/>';
}
?>
我試圖生成形式star.word1.word2,其中字詞1是從數據庫中隨機單詞,單詞2是從數據庫(字詞不同的隨機字三個詞組合!= WORD2)。然後將生成的每個組合分配給數據庫中的星形。
如何避免重複組合?通過重複組合,我的意思是:
組合1:star.lamp.chair;組合2:star.dog.ball;組合3:star.ball.dog;組合4:star.lamp.chair
在這裏,組合1和組合4是相同的 - 這種重複是我想要避免的。順序並不重要,所以組合2和組合3都很好。
你能提供您使用的代碼重複的過程?必須有一些循環或請求發生才能獲得多個請求? – trincot
或'shuffle'數組和'array_slice' – splash58
我假設你從某種應用程序多次調用此腳本以獲得多個組合?如果是這樣,您可以保存所有已經生成的組合,並檢查新組合是否與其中任何組合相同。如果是,則創建一個新組合。 – GregaMohorko