douran9707 2013-07-22 13:33
浏览 62
已采纳

PHP生成随机用户名

I am doing a little function to generate random usernames, as the following:

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);
    }

}

The only problem I have is that $random is just executed one time and not on each loop. I need 3 different usernames to be in the array, and they must be different from each other. How can I edit my code to achieve this? Thanks for any suggestion

  • 写回答

2条回答 默认 最新

  • dpvv37755 2013-07-22 13:36
    关注

    Place the random number generator and nickname building variable at the start of your loop. Also increase the range of numbers that rand is allowed to return, as it will always return 2 at the moment

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?