drui0508 2015-07-09 18:49
浏览 24
已采纳

如何生成随机唯一字符串列表? [关闭]

I'm using this function to create a random string, but how would I make it to generate a unique string list for a 500 strings?

function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
  • 写回答

3条回答 默认 最新

  • dsztc99732 2015-07-09 19:06
    关注

    If you are worry about inserted rows in table then there are 3 simple ways to do it.

    First way, you can check if the string exists in db then create another random string.

    Second way, use UUID() function of mysql that generates random value and there's no need to worry about duplication.

    Third way, if you want the array, generate 500 string and put in an array. then use array_unique() to remove duplication. If array length was < 500 then generate more (for example 12 strings) then check if < 500 again and again until it reaches exactly 500. Checking can be done in a while loop or so.

    while( count($arr) < 500 )
    {
        $arr[] = generateRandomString();
    
        if( count($arr) == 500 )
            $arr = array_unique( $arr );
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?