我需要为每个用户生成一个唯一的扩展名(这与ID分开,但工作原理大致相同)该数字应为100或更大,并且可以覆盖/自定义设置。现在我正在获取下一个 id,如果它小于 100,则添加 100。
因此,如果下一个 id 是 5,则数字将是 105,但下一个 id 是 105,则数字只是 105。问题是,因为如果用户选择 105,我会让用户选择自己的分机号,然后我想让它自动跳转到下一个数字,在本例中为 106。现在,如果有 105、106 和 108,我想跳到 107,然后跳到 109。 这是我用来生成数字的代码。我认为问题出在我的 while 循环上。我不确定如何让它继续检查唯一数字。
这是代码,我确定我把事情复杂化了很多。
$result = mysql_query("SELECT MAX(id)
FROM USERS");
$row = mysql_fetch_row($result);
$sql_extention = intval($row[0]);
//make sure it's at least 100
$extension = ($sql_extension < 100) ? $sql_extension+100 : $sql_extension;
//check to see if the extention is in use
$qry = "SELECT `extention`
FROM users
WHERE extention = '$extention'";
$result2 = mysql_query($qry);
//if the extention is in use then find the next available one (this isn't currently working)
if($result2) {
//get all results greater or equal to our extention
$qry3 = "SELECT `id`,`extention`
FROM admin_users
WHERE extention >= '$extention'";
$result3 = mysql_query($qry3);
//this loop needs to be rewritten somehow to get the next number by checking if the next number exist if not return that as the extention
$new_extention = $extention+1;
while($extention_data = mysql_fetch_array($result3)) {
if($new_extention != $extention_data['extention']+1) {
$extention = $new_extention;
}
$new_extention++;
}
出了这个,还没有彻底测试它,但我认为它应该正确返回下一个可用值
SELECT (a.extention + 1) as avail
FROM admin_users a LEFT JOIN admin_users b on ( (a.extention + 1) = b.extention )
WHERE a.extention >= 105 and b.extention is null
ORDER BY avail ASC
LIMIT 1
因此,如果这按预期工作,您根本不需要最后几行代码。
编辑:修改了查询,因为我意识到我从错误的一侧接近它。
我的评论,对 PHP/伪代码示例的劣质尝试:
//nicer way to get the id of the user you just inserted!
$id = mysql_insert_id();
$sql = "SELECT `extension` FROM users ORDER BY `extension` ASC";
$res = mysql_query($sql);
$i=0;
while($n = mysql_fetch_array($res)){
if($i==0){
$i=$n['extension'];
}
if($i==$n['extension']){
$i++;
} else {
break;
}
}
//No existing users, start at 100
if($i==0){
$i=100;
}
然后使用 $i 作为扩展。
好的,所以你需要下一个可用的扩展名,高于给定的数字,该扩展名尚未在数据库中。因此,理想情况下,您希望数据库中的数组具有高于给定键升序排序的可用扩展名。然后从给定的数字开始循环,增加 1,直到它不匹配。您没有提到最大扩展数。我会这样做:
<?php
$rs = mysql_unbuffered_query("SELECT extention, MAX(extention) FROM admin_users WHERE extention > '$extention' ORDER BY extention ASC");
$unavailable = array();
$max = 0;
while( ($row = mysql_fetch_row($rs)) )
{
$unavailable[] = $row[0];
if( !$max ) $max = $row[1];
}
mysql_free_result($rs);
// Optimization for the quite common case where no more extentions are available
if( count($unavailable) > 0 )
{
while($extention <= $max+1)
{
if( !in_array($extention, $unavailable) )
break;
$extention++;
}
}
else
$extention = $max+1;
// Worst case: $extention now is max + 1 and we looped through almost everything.
?>