由于我的网站没有上线,我无法提供 HTML。虽然我从理论编码中知道,专业人士希望能够遵循我的逻辑。
- 请用我的代码指出我如何使它工作,因为我看到以下链接是相似的,但不完全相同的场景。我很困惑如何将它应用于我的以下代码:
我的目标 我想使用 PHP 创建以下内容:
- 将 00 到 99 放入一个数组中。
- 从数组中检索一个随机数。
- 存储/使用从数组中检索到的随机数以放置在 mysql_query 中,如number = $question注意这里所示(我真的需要 ORDER BY RAND() 吗?)
- 从数字数组列表中删除选定的随机数
- 获取并显示随机数
- 使用完所有号码后,会显示一条错误消息,提示刷新页面以重置号码。
下次我想要另一个随机数时,它不能复制它之前从数组中选择的相同随机数。因此,如果我使用上面的代码说 109 次,那么数组中只剩下 1 个数字。
代码(已编辑):
<?php
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "monkeyscanfly";
$tableName = "num_image";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(!isset($_SESSION)) {
session_start();
$_SESSSION['used'] = [];
}
$array = [0,1,2,3,4,5,6,7,8,9,"00","01","02","03","04","05","06","07","08","09",10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99];
while(!empty($array)) {
$array = array_diff($array, $_SESSSION['used']);
//pick a random point from the array
$random = array_rand($array);
// Save the used element in session
$_SESSION['used'][] = $array;
//store the random question number
$question = $array[$random];
// Select information from database and use array to assign to the selected row.
$query = mysql_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE number = $question ORDER BY RAND() LIMIT 1");
// Remove random number that was chosen from the array, so the next time the random number is ran, it won't be found in the array.
unset($array[$random]);
//fetch result to print on page
$arrayss = mysql_fetch_row($query);
//Echo result as json
echo json_encode($arrayss);
}
if(count($array) == count($_SESSION['used'])) {
$_SESSION['used'] = [];
}
?>
我希望这是有道理的,我很难找到如何去做,我已经搜索了几个小时,无法理解它。:)
我忘了提到每次我需要一个新的随机数时,这个 PHP 脚本都会被 ajax 代码重新加载。所以它必须记住这一点来存储/记住数字。如果这有意义吗?