x = 1到20的PHP循环

我正在寻找一种简化方法。

    $token2h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token3h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token4h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token5h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token6h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token7h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token8h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token9h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token10h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token11h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token12h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token13h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token14h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token15h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token16h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token17h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token18h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token19h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    $token20h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);

我尝试了各种方法来制作循环,但似乎无法使其正常工作。

评论
沉默U
沉默U

You can do this way with range() and extract(),

<?php
$range = range(2,20);
foreach($range as $k){
    $tokens["token{$k}h"] = substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
}
print_r($tokens); // full list of tokens inside an array
extract($tokens); //make array to variables for future use
echo "token10h is = $token10h";
?>

WORKING DEMO: https://3v4l.org/cvKmo

点赞
评论
游欣彤
游欣彤

You can use for loop to make it simplifed

<?php
    for ($i= 1; $i < 20; $i++) { 
        $token2h=substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
    }  
?>
点赞
评论
Orz
Orz

我认为方法是在动态变量名称上:

<?php
for ($i= 2; $i <= 20; $i++) 
{ 
    ${'token'. $i .'h'} = substr(str_shuffle("0p23456789ABCDEFGHIJKLMNoPQRSZUVWXYZ"), 0, 20);
}  
?>
点赞
评论