简体   繁体   English

同时循环遍历 3 个数组 php

[英]Looping through 3 arrays at the same time php

A total noob question, but here I go:一个完全的菜鸟问题,但我走了:

I have 3 arrays (numbers, the alphabet and other characters), the usual.我通常有 3 个数组(数字、字母和其他字符)。

I need to basically come up with code that will create a random password.我需要基本上想出可以创建随机密码的代码。 And I have to have the 3 arrays... how do I loop through them to get a character from each?而且我必须有 3 个数组……我如何遍历它们以从每个数组中获取一个字符? I'm confused, please someone point me to the right direction.我很困惑,请有人指出我正确的方向。 Thanks谢谢

So we will loop N times and pick out a rand value from each array you have所以我们将循环 N 次并从您拥有的每个数组中挑选出一个 rand 值

<?php
$length = 32; //length of random password 
$a1 = str_split('0123456789'); // convert to array
$a2 = str_split('%^*+~?!'); //convert to array
$a3 = str_split('abcdefghigklmnopqrstuvwxyz'); // convert to array

$result = ""; //final random password

for($i = 0; $i < $length; $i++){
    //choose random array from the three a1, a2, a3
    //then choose random value from the chosen array
    // note: array_rand is a built-in PHP function
    // that accepts an array as the first parameter
    // and number of random elements to pick out 
    // as a second optional parameter that defaults to 1
    $values = [$a1,$a2,$a3];
    $chosen = array_rand($values);

    $result .= $values[$chosen][array_rand($values[$chosen])];
}
 //print the result out
 echo $result;

?>

I hope this will help!我希望这个能帮上忙!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM