根据用户的个人资料,我想查看其个人资料中的列是否包含某些字词,如果有,请从特定表中选择一个随机条目。
另外,最后,我想只打印其中一个条目。因此,如果他们的个人资料包含所有5个单词,我希望PHP每次刷新页面时仍然只打印一个随机条目。
有人可以指出我正确的方向吗?我现在的代码如下:
<?php
session_start();
include 'includes/Connect.php';
$username=$_SESSION['myusername'];
$query = "SELECT `CC` FROM `$username`";
$result = mysql_query($query);
$pos1 = strpos($result,'Honesty');
$pos2 = strpos($result,'Loyalty');
$pos3 = strpos($result,'Trust');
$pos4 = strpos($result,'Empathy');
$pos5 = strpos($result,'Respect');
while($Aff = mysql_fetch_array($result)){
$data = array();
if($pos1!==false){
$query1 = "SELECT Affirmation FROM `Aff CC1` ORDER BY RAND() LIMIT 1";
for ($x = 0; $x < mysql_num_rows($query1); $x++)
{
$data[] = mysql_fetch_assoc($query1);
}
}
if($pos2!==false){
$query2 = "SELECT Affirmation FROM `Aff CC2` ORDER BY RAND() LIMIT 1";
for ($x = 0; $x < mysql_num_rows($query2); $x++)
{
$data[] = mysql_fetch_assoc($query2);
}
}
if($pos3!==false){
$query3 = "SELECT Affirmation FROM `Aff CC3` ORDER BY RAND() LIMIT 1";
for ($x = 0; $x < mysql_num_rows($query3); $x++)
{
$data[] = mysql_fetch_assoc($query3);
}
}
if($pos4!==false){
$query4 = "SELECT Affirmation FROM `Aff CC4` ORDER BY RAND() LIMIT 1";
for ($x = 0; $x < mysql_num_rows($query4); $x++)
{
$data[] = mysql_fetch_assoc($query4);
}
}
if($pos5!==false){
$query5 = "SELECT Affirmation FROM `Aff CC5` ORDER BY RAND() LIMIT 1";
for ($x = 0; $x < mysql_num_rows($query5); $x++)
{
$data[] = mysql_fetch_assoc($query5);
}
}
}
?>
所以我这样做了,而我仍然没有得到任何东西。
session_start();
include 'includes/Connect.php';
$username=$_SESSION['myusername'];
$query = "SELECT `CC` FROM `Profile` where `Username`=`$username`";
$result = mysql_query($query);
$pos1 = strpos($result,'Honesty');
$pos2 = strpos($result,'Loyalty');
$pos3 = strpos($result,'Trust');
$pos4 = strpos($result,'Empathy');
$pos5 = strpos($result,'Respect');
$data = array();
for ($x = 0; $x < mysql_num_rows($result); $x++) {
if($pos1!==false){
$CCID=1;
}
if($pos2!==false){
$CCID=2;
}
if($pos3!==false){
$CCID=3;
}
if($pos4!==false){
$CCID=4;
}
if($pos5!==false){
$CCID=5;
}
$querymain = "SELECT `Affirmation` FROM `Affs` WHERE CCID=$CCID ORDER BY RAND() LIMIT 1";
$resultmain = mysql_query($querymain);
for ($x = 0; $x < mysql_num_rows($resultmain); $x++)
{
$data[] = mysql_fetch_assoc($resultmain);
}
}
echo json_encode($data);
mysql_close($conn);
?>
答案 0 :(得分:1)
好的,所以你有一个数量最多X项的数组。您可以从数组中选择一个随机项,类似于从数据库中选择随机项的方式。
基本上,只需对$data
数组进行计数即可查看其中有多少项目。然后选择一个介于0之间的随机数,然后选择多少个项目,减去1.您现在可以从数组中访问该特定项目。
在构建$data
数组之后尝试这样的事情:
<?php
$line_count = count($data) - 1;
print "RANDOM LINE: ".$data[get_random_line($line_count)];
function get_random_line($line_count) {
mt_srand(microtime() * 1000000);
$random_number = rand(0, $line_count);
return $random_number;
}