这里我的我的用于产生三个词的组合(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