4

我正在做一个小功能来生成随机用户名,如下所示:

public static function nicknames($data) {
    if ($data['request'] == 'nickAvailable') {

        foreach ($data as $value)
            if (is_array($value))
                $nick = $value['nickname'];

        $random = rand(2, 2);
        $nickname = $nick . '_' . $random;

        $count = 3;
        $nicknames = array();
        for ($i = 1; $i <= $count; $i++) {
            $select = self::$db->select('users', 'nickname', array('nickname' => $nickname));

            if (count($select) == 0) {
                $nicknames[] = $nickname;
            } else {
                $count = $count + 1;
            }
        }

        $array = array("status" => 0,
            "errors" => $nicknames,
            "data" => array());

        model::json($array);
    }

}

我唯一的问题$random是只执行一次,而不是在每个循环上执行。我需要 3 个不同的用户名在数组中,并且它们必须彼此不同。如何编辑我的代码来实现这一点?感谢您的任何建议

4

2 回答 2

1

将随机数生成器和昵称构建变量放在循环的开头。还要增加 rand 允许返回的数字范围,因为它现在总是会2返回

$usernames = array();
do {

 // inside generate random number, 
 // build nickname, 
 // query to see if its taken, 
 // and if NOT taken, add to the usernames array

} while(count($usernames) < 3);
于 2013-07-22T13:36:00.240 回答
1

到目前为止,您还没有生成随机数。

$random = rand(2, 2);

这将永远是2

这是我的做法:

for ($i = 1; $i <= $count; $i++) 
    {

    $random = rand(1, 3);
    $nickname = $nick . '_' . $random;
        $select = self::$db->select('users', 'nickname', array('nickname' => $nickname));

        if (count($select) == 0) {
            $nicknames[] = $nickname;
        } else {
            $count = $count + 1;
        }
    }

希望这可以帮助!

于 2013-07-22T13:42:53.130 回答