根据设置概率选择用户

时间:2013-04-18 11:43:52

标签: php mysql arrays probability

我的数据库存储有关用户,他们的群组和关系的信息。 users表中的一列fcount跟踪每个用户在其当前组中的关系数量;它从0开始,我在适当时增加它 我需要编写一个脚本来选择给定组中的所有用户,然后随机选择其中一个,并根据已经拥有的关系数量选择其中一个;关系越少意味着概率越大。

目前,我使用以下代码完成此操作,减去概率部分:

$query = "SELECT uid FROM users WHERE groupid=:gid AND status='1'";
...
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
    $friends[] = $row[0];
}

foreach ($users as $value) {
    $key = array_search($value, $friends);
    unset($friends[$key]);
    shuffle($friends);
    $newrel = end($friends);
    $user = $value;
    $friends[] = $value;

    $query = "UPDATE users SET rel=:newrel WHERE uid=:uid";
    $query_params = array(':newrel' => $newrel, ':uid' => $user );
... }

我认为调整概率的最简单方法是编辑$friends数组,以便用户不止一次出现。因此,fcount为0的用户将在阵列中重复5次,而fcount为1的用户将重复3次。 [也许这不是处理它的最好方法,但它对我来说很合理并且符合我已有的代码。你可以自由地提供更好的方案。]

我还没弄清楚如何获取用户数组并乘以应该乘以的用户的条目。

SELECT uid, fcount FROM users WHERE groupid=:gid AND status='1';

返回一个反映此表的数组:

+-----+--------+
| uid | fcount |
+-----+--------+
| 105 |      3 |
| 106 |      2 |
| 107 |      0 |
| 108 |      0 |
| 109 |      1 |
+-----+--------+

然后变成这样的数组:

array(15) { 
[0]=> string(3) "105" 
[1]=> string(3) "106" 
[2]=> string(3) "107" 
[3]=> string(3) "107" 
[4]=> string(3) "107" 
[5]=> string(3) "107" 
[6]=> string(3) "107" 
[7]=> string(3) "108" 
[8]=> string(3) "108" 
[9]=> string(3) "108" 
[10]=> string(3) "108" 
[11]=> string(3) "108"
[12]=> string(3) "109" 
[13]=> string(3) "109" 
[14]=> string(3) "109" 
}  

在我看来,这可以通过foreach完成,该{{1}}根据循环中的if语句将每个userid n 次推送到新数组中。我会尝试构建它,即使我可能会失败。

2 个答案:

答案 0 :(得分:1)

$problist = array();
foreach ($row as $value) {
    if ($value['fcount'] == 0) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] == 1) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] >= 2) {
        $problist[] = $value['uid'];
    }
}

答案 1 :(得分:0)

在一般情况下计算概率的最简单方法

$relations = 10;
$chance = rand(1,100);
if ($chance <= $relations) {
// success
}

在这种情况下,关系越多,概率越大,就像$ relations = 99,你有99%的概率用关系= 99来击中这个用户