dongwenxiu5200 2015-06-16 06:14
浏览 344
已采纳

使用foreach连接字符串

I'm trying to make a generated random characters. I'm concatenating the values of $char_type using foreach loop but it doesn't show anything. Here's my code:

    public function randomizer($range, $type) {
     $strtester = '';
     $char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz',
                        'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                        'num'    => '0123456789',
                        'sp'     => '!@#$%^&*()');

     if(is_array($type)) {
         foreach($type as $row) {
             if(in_array($row, $char_type)) {
                 $strtester .= $char_type[$row];
             }
         }
     }
     print_r($strtester); exit();
     $seed = str_split($strtester);
     shuffle($seed);
     $generated_string = '';
     foreach (array_rand($seed, $range) as $k) $generated_string .= $seed[$k];

     return $generated_string;
    }

Update: What i want to get from $strtester is for example I want $char_type alp_sm and alp_cs then the $strtester will get abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Thank you in advance

  • 写回答

4条回答 默认 最新

  • douwen7603 2015-06-16 06:47
    关注

    Replace if(in_array($row, $char_type)) { to if(array_key_exists($row, $char_type)) { and then try

        function randomizer($range, $type) {
             $strtester = '';
             $char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz',
                                'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                                'num'    => '0123456789',
                                'sp'     => '!@#$%^&*()');
    
            if(is_array($type)) {
                foreach($type as $row) {
                    if(array_key_exists($row, $char_type)) {
                        $strtester .= $char_type[$row];
                    }
                }
            }
    
            $seed = str_split($strtester);
            shuffle($seed);
            $generated_string = '';
            foreach (array_rand($seed, $range) as $k) 
                $generated_string .= $seed[$k];
            return $generated_string;
        }
    
        $res =  randomizer(5, array("alp_sm"));
        print_r($res);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了