我正在做一个小函数来生成随机用户名,如下所示:
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个不同的用户名才能在数组中,它们必须彼此不同.
如何编辑我的代码来实现这一目标?
谢谢你的任何建议
最佳答案 将随机数生成器和昵称构建变量放在循环的开头.同时增加允许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);