php循环问题

标签 php mysql loops

请原谅框架特定的代码。请相信我的话,对象按照我说的去做。

我的代码

       //Generates a random five digit alphanumerical id
       $aliasId = $model->random_id_gen('5');

       //calls the active record class for table Person                     
       $person = new Person();

       //searches the person table to see if this alias is being used         
       $search = $person->find('alias=:alias', array(':alias'=>$aliasId));

       //if null then it sets an attribute for a another active record class                     
       if ($search==NULL)
       {
               $model->setAttribute('alias', $aliasId);
               $model->setIsNewRecord(TRUE);
       }
       else
       {
       //I need to loop through the above code until I find an alias that isn't being used                            
       }

我的问题

我在 else 语句中写了什么来运行上面的代码,直到我找到一个没有在 Person 表中使用的别名。我的猜测是某种循环,但我不确定该怎么做。随意按照你喜欢的方式重新工作。把它作为自己的功能/告诉我我做错了,我不会被冒犯。谢谢!

最佳答案

$found = false;
$iter = 0;        // It's a good idea to include an upper bound on the number of iterations
while(!$found && $iter < 1000){
   $aliasId = $model->random_id_gen('5');

   //calls the active record class for table Person                     
   $person = new Person();

   //searches the person table to see if this alias is being used         
   $search = $person->find('alias=:alias', array(':alias'=>$aliasId));

   //if null then it sets an attribute for a another active record class                     
   if (is_null($search)){
       $model->setAttribute('alias', $aliasId);
       $model->setIsNewRecord(TRUE);
       $found = true;
   }
   $iter++;
}

if(!$found){ /* Some error condition because a suitable ID could not be found*/ }

但是,如果不必随机生成别名 ID,则使用自动递增的值可能是更好的主意。

将数字与 base36 相互转换你可以使用 PHP 的 base_convert功能:

$a = base_convert(12345,10,36);
$b = base_convert($a,36,10);
print "12345 --> ".$a."  --> ".$b;

输出:

12345 --> 9ix  --> 12345

如果您想确保您的号码至少为 5 位数字,请从以下位置开始您的增量值:base_convert(10000,36,10) = 1679616

关于php循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6526067/

相关文章:

php - CodeIgniter 和多语言数据库

php - 如何在android中比较JSON对象和字符串?

mysql 5.6 更改 lower_case_table_names 不起作用

javascript - iMacros 中的嵌套循环(第二个循环)

php - 在 PHP DOM 中过滤日期

php - 登录后如何访问特定的mysql数据行和列?

java - 在 Hibernate 中映射一对多关系?

javascript - 使用 JavaScript Prototype 库循环遍历所有选择元素

java - 尽管使用了安全removeIF,但出现了ConcurrentModificationException

php - 安装表并防止 2 列的重复输入