douye2110 2019-05-24 15:35
浏览 116
已采纳

我有一个生成随机字符串的函数,我希望它生成超过1行的随机字符串

I have a Function to generate random string ,it produce more than 1 random string ,but how to separate them

    Function generatorstring($count) {

    $karakter = '0123456789abcdefghijklmnopqrstuvwxyz';
    $length = 7;
    $randomString = '';

    for ($i=0; $i <$count ; $i++) { 

        for ($ia = 0; $ia < $length; $ia++) {
            $randomString .= $karakter[rand(0, strlen($karakter) - 1)];
        }

    }

    return $randomString ;
}
echo generatorstring(3);

I expected result like this

'As6s8Xs',
'zE71jnM', 
'ak9a71b', 

But, its only produce 1 line of random string.

  • 写回答

2条回答 默认 最新

  • douxu2467 2019-05-24 15:59
    关注

    Well, right off the bat, your biggest problem is that you have a for loop using a variable that is inside a for loop using the same variable.

    First for loop establishes $i as 0, incrementing 1. Second for loop (inside) overwrites $i as 0 and increments until $i equals $length. $i is now 7. Outer for loop sees $i is 7, which is greater than $count (3), therefore the outer for loop breaks.

    for($i=0; $i < $count; $i++) {
       for($ia=0; $ia < $length; $ia++){
          //do something
       }
    }
    

    Also note, this is ugly, and it is better, as @dWinder mentioned, to put your inner for loop in its own function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料