好吧,我不会撒谎,但我不知道我该怎么做,我使用PHP和SQL,在一个SQL表中有一些值,例如:
+----+----------+-----------+
| ID | username | presentid |
+----+----------+-----------+
| 1 | user1 | 1 |
| 2 | user2 | 1 |
| 3 | user1 | 2 |
| 4 | user2 | 2 |
| 6 | user3 | 2 |
| 7 | user4 | 1 |
| 8 | user6 | 1 |
| 9 | user7 | 1 |
| 10 | user13 | 1 |
| 11 | user11 | 2 |
| 12 | user14 | 2 |
| 13 | user9 | 1 |
| 14 | user15 | 1 |
| 15 | user5 | 2 |
| 16 | user5 | 1 |
+----+----------+-----------+
其中username
是帐户用户名,presentid
是现在"抽奖"。
我需要的是能够按顺序获取值的东西,例如,让所有加入当前用户的用户:
+----+----------+-----------+
| ID | username | presentid |
+----+----------+-----------+
| 1 | user1 | 1 |
| 2 | user2 | 1 |
| 7 | user4 | 1 |
| 8 | user6 | 1 |
| 9 | user7 | 1 |
| 10 | user13 | 1 |
| 13 | user9 | 1 |
| 14 | user15 | 1 |
| 16 | user5 | 1 |
+----+----------+-----------+
因此,按顺序加入所有这些应该始终有一个特定的数字,例如在上面的例子中它将是:
1 = user1
2 = user2
3 = user4
4 = user6
5 = user7
6 = user13
7 = user9
8 = user15
9 = user5
这个顺序应该是唯一的,因为它是他们加入当前抽奖的顺序,我想在PHP页面中显示该订单中的用户的数字,然后我想使用该顺序并选择一个随机数从1到9,因为只有9个用户加入。
有可能吗?如果是,有人可以给我一些帮助,我想用PHP做。
我真的需要知道如何做到这一点,为用户订购。
使用@Babydead提供的代码:
$querythis = $db->query('SELECT * FROM `users_giveaways` WHERE `presentid`= 1');
$results = $querythis->fetch();
$presentGroups = array();
foreach($results as $r){
$presentID = $r['presentid'];
$userID = $r['username'];
$presentGroups[$presentID][] = $userID;
$string=implode(",",$results);
echo $string;
}
foreach($presentGroups as $presentID => $usersArray){
$arrayLength = (count($usersArray));
$randomNumber = mt_rand(1, $arrayLength) - 1;
echo $usersArray[$randomNumber] . "has been selected for $presentID !!! <br/><br/>";
}
我得到了这个结果:
Warning: Illegal string offset 'username'...
和
Warning: Illegal string offset 'presentid'...
但我有这些专栏。
答案 0 :(得分:2)
首先,您从MYSQL
查询获得所有结果,我假设您知道它是如何工作的(否则只是问:))
现在,在PHP上,您可以将当前ID和用户ID分成如下组:
$presentGroups = array();
//Loop through query results
foreach($results as $r){
$presentID = $r['presentid']
$userID = $r['username']
//Put the users in sub-arrays by presentID
$presentGroups[$presentID][] = $userID;
}
现在,您可以从阵列中抓取一个随机用户并瞧不起;自动抽奖。
//Let's get some results going.
//Get the presentID's (key of created array) and the users coupled with it
foreach($presentGroups as $presentID => $usersArray){
//Get the length of the current array for the random number generator
$arrayLength = (count($usersArray));
//Generate random number
$randomNumber = mt_rand(1, $arrayLength)) - 1;
//Grab any array index through the generated random number
echo $usersArray[$randomNumber] . "has been selected for $presentID !!! <br/><br/>";
}
我还没有测试过这个,但它应该有点像这样,不是吗?