我想在php中动态使用 foreach 循环,我有权将AAA打印到 999 ,并且我正在使用此代码及其工作完美,
Reference :: http://www.onlinecode.org/generate-string-aaaa-9999-using-php-code/
$addalphabeth = array_merge(range('A', 'Z'), range(0,9));
$setcharacter = [];
foreach ($addalphabeth as $setcharacter[0]) {
foreach ($addalphabeth as $setcharacter[1]) {
foreach ($addalphabeth as $setcharacter[2]) {
//$setcatalog[] = vsprintf('%s%s%s', $setcharacter);
echo "<b>".vsprintf('%s%s%s', $setcharacter)."</b>";
echo "<br>";
}
}
}
现在我的问题是必须将 AAAAA 打印到 99999 (需要循环5次)或 AAAAAAAA 打印到 99999999 (需要循环8次), 所以对于这个我使用循环 n时间。我不知道该怎么做,任何帮助或建议将不胜感激。
答案 0 :(得分:1)
Evening, here is my solution, using recursion. To setup a recursion, you have to think of two things. What is your stop condition, and what do to with non-stopping conditions.
So here is the code:
function printAto9($width,$prefix = '')
{
$chars = array_merge(range('A', 'Z'), range(0,9));
if ($width == 1)
{
foreach ($chars as $char)
{
echo "$prefix$char\n";
}
}
else
{
$width--;
foreach ($chars as $char)
{
echo printAto9($width,$prefix . $char);
}
}
}
printAto9(5);
I put printAto9(5);
as a test, you can use whatever.
But careful, the output is monstrous pretty quick, and you can kill your php (memory or time limit).