我正在做一个小函数来生成随机用户名,如下所示:
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个不同的用户名才能在数组中,它们必须彼此不同。
如何编辑我的代码来实现这一目标?
感谢您的任何建议
答案 0 :(得分: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);
答案 1 :(得分: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;
}
}
希望这有帮助!