Unique id consisting of only numbers

限于喜欢 提交于 2019-12-11 05:53:51

问题


I need to get time based unique id which would only consist of numbers, i was thinking to simply use something like this:

str_replace(".", "", microtime(true))

I would use this id for many things, for example comments posting, and i'm expecting quite high traffic so i would like to know how high are the chances of collision with microtime function?

And perhaps there is a better way to get numerical unique id? Just remember that it has to based on time so sorting could be done.


回答1:


If you need to use a pure time based ID you need to ensure that you avoid collisions so a) use a primary key in the database and then b) use a recursive check to ensure that your time based ID has not already been taken:

$id = getTimeId();

function getTimeId() {
    // Generate microtime
    // Query to ensure it does not exist
    // Return microtime
}

I shall leave it upto you good sir to enjoy making it recursive.




回答2:


you can use this to get uniqid but is not numberic:

$id = uniqid(); //58aea16085f6b

use this to convert it to only numbers:

$id = hexdec( uniqid() ); //1560112880181100

if it's too long use this but maybe get negetive numbers:

$id = crc32( uniqid() ); //-1551585806

if you just need posetive numbers you can do it:

$id = abs( crc32( uniqid() ) ); //1551585806



回答3:


If it must be based on time you could use microtime. But I guess you are storing things in a database so my vote would go for a primary key column Id with auto_increment and then a second column with timestamp type and a default current time.

Then you can sort on timestamp and also have a 100% unique identifier even with extremely high traffic. But if ordering is needed (so not searching between dates) then you dont need it based on time.

1, 2, 3, 4 will be in the same order as a microtime key thats just a lot larger and further appart.

UPDATE

If it must be a unique key and cant be used from the database, try the following. The changes of a duplicate key are so slim it can be ignored.

$key = microtime() + floor(rand()*10000);



回答4:


if you have to avoid collisions time based won't work. eventually you'll get a collision. Why not use a counter with a semaphore.

http://php.net/manual/en/book.sem.php



来源:https://stackoverflow.com/questions/13932259/unique-id-consisting-of-only-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!