Zend Framework生成独特的字符串
我想生成一个唯一的4-6个char长字母数字字符串,以保存每个记录(用户)中的DB。 DB字段具有唯一的索引,因此尝试保存预先存在的字符串会生成错误。现在,我正在生成一个随机字符串并使用try-catch,因此在添加新记录时,如果引发异常,我会生成另一个随机字符串并尝试再次保存,并且代码继续尝试,直到成功添加记录为止。整个解决方案不仅看起来很重,而且很丑陋,所以我想更改它。我对优雅的解决方案感兴趣,因此欢迎任何帮助/指导。
I want to generate a unique 4-6 char long AlphaNumeric string to save in db with each record(user). The db field has a unique index, so trying to save a pre-existing string generates an error. Right now I am generating a random string and using try-catch, so when adding a new record if it throws an exception, I generate another random string and attempt to save again, and the code keep trying until it adds a record successfully. This whole solution not only looks heavy but also ugly, so I want to change it. I am interested in an elegant solution, so any help/guidance is welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用给定的信息:
PHP函数
** 编辑 **
是的,
uniqid
将返回一个接缝的顺序编号,但是我们可以轻松解决这个问题。考虑此代码,该代码将带来结果,
因为没有任何添加或修改的代码,除了整理位置外,不应有任何重复的值,而且一切似乎都是随机的。瞧!
** UPDATE(2014-02-24)**
我自最初发布的时间以来更新了此代码。您可能会发现修订版在这里
With the given information :
The PHP function uniqid is exactly what you need. Though it returns a 13 character long hexadecimal value.
** Edit **
Yes,
uniqid
will return a seamingly sequential number, but we can get around this easily. Consider this codeWhich will give results like
Since there is nothing added or modified, except shuffling the bits around, there should not be any duplicated values and everything seems random. Voilà!
** Update (2014-02-24) **
I update this piece of code since the time it was originally posted. You may find the revised version here