php - 如何使用 PHP 创建随机分配的名称?
问题描述
我有一个关于使用 PHP 在我的数据库中随机分配用户的问题。我想创建一个网站,人们在第一步中输入用户数量,在第二步中输入这些用户的姓名。然后名字应该随机混合,每个名字都被分配了一个不同的名字(绝对不能发生这种情况:让你自己或一个人被分配两次)。这个网站是我家人的一个小项目。当我们做某种绘画时,我们总是可以在圣诞节使用它们。每个人都从参与者那里抽出一个名字,然后为被抽中的人获得一份礼物(我不知道它在英语中是怎么称呼的。在德国我们说“wichteln”:D)。不幸的是,我不知道如何在 PHP 中做到这一点。
到目前为止,在第一步中,我已经询问了有多少参与者。然后它检查输入的数字是否是 2 到 49 之间的数字。在第二步中,给出参与者的姓名。输入所有名称后,单击按钮(名称 = teilnehmerdetails)。然后进行以下操作:
if(isset($_POST['teilnehmerdetails'])) {
$datetime = date("Y-m-d H:i:s");
$date = date("Ymd");
$time = date("His");
$generatorid = $date . $time;
$name = $_POST['name'];
foreach( $name as $key => $n ) {
$teilnehmerid = $key + 1;
$query = "INSERT INTO member (generator_id, date, userid, name) VALUES ('$generatorid', '$datetime', '$teilnehmerid', '$n')";
$query_conn = mysqli_query($connection, $query);
if(!$query_conn) {
die("Query failed" . mysqli_error($connection));
}
echo $teilnehmerid.". Teilnehmer: ".$n;
echo "<br>";
}
}
参与者现在存储在数据库中。使用变量 $generatorid,我可以看到哪些参与者属于请求。
如何混合输入的名称并为每个名称分配一个新名称?
例如,输入以下名称:人员 1、人员 2、人员 3、人员 4
随机结果是:第 1 个人有第 3 个人,第 2 个人有第 1 个人,第 3 个人有第 4 个人,第 4 个人有第 2 个人
解决方案
好吧,我很高兴在 5 个多月没有编码后让这个工作正常进行。代码已在我的 Web 主机上进行了测试。
// I first tried to do just a single select but I landed on rocks so I decided to do double
$get_member_names = mysqli_query($connection, "SELECT name FROM member");
// Get the member names so that we can place them in an array
$get_members = mysqli_query($connection, "SELECT * FROM member");
// This second select will enable us to place random member names to the userids
$member_names = array();
$members = ''; // Initiate the variable which will display the output
if(mysqli_num_rows($get_member_names) > 0){
while($row_names = mysqli_fetch_array($get_member_names)){
// Place now the names into the array
$member_names[] = $row_names['name'];
}
}
if(mysqli_num_rows($get_members) > 0){
while($row_members = mysqli_fetch_array($get_members)){
$user_id = $row_members['userid'];
$memberName = $row_members['name'];
// Get the key for the corresponding names
$memberName_index = array_search($memberName,$member_names);
// Use the key to remove the current name from the names array
unset($member_names[$memberName_index]);
// Change the positions of the remaining names in the array
shuffle($member_names);
// Get the new name at position 1. You can replace 0 with say 3 if you like
$get_the_new_position_1_name = $member_names[0];
// Give the name to the userids
$members .= $user_id . ' - ' . $get_the_new_position_1_name . '<br />';
}
// Display result
echo $members;
}
推荐阅读
- c# - 如何在 C# 中使用 WorksheetFunction.CountIf?
- flutter - Flutter - 在日期时间选择器时间轴中仅显示月份
- rust - Rust:用函数修改引用的引用对象;这是否包含UB?
- sql - 记录特定用户访问的单个数据库 postgresql 中所有表的查询
- c# - 如何在 WPF 中的控件上使用 Light?
- python - 对部分多索引数据框的熊猫操作
- javascript - 从 JS 动态创建 svg 不适用于剪辑路径
- c++ - 新行上的 clang-format columnlimit 返回类型
- python-3.x - 升级到 Mac OS 11 (Big Sur) 后,OpenCV 无法与 PyCharm 一起使用
- javascript - 使用 Object.entries 遍历对象