我要做的是以下内容:我有一个值数组,这些值最终将用于生成随机唯一字符串,但稍晚一些。首先,我想循环遍历数组中的所有值(foreach循环),然后我想限制它(while循环)这是一个正确的方法吗?
以下代码不起作用,任何人都可以看到我做错了吗?
<?php
$array = array(
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '!', '£', '$', '%',
'^', '&', '*', '(', ')', '_', '+', '{', '}'
);
$length_of_unique_key = 15;
$counter = 0;
foreach($array as $values)
{
$counter++;
while ($counter <= $length_of_unique_key)
{
}
}
?>
答案 0 :(得分:11)
你不应该在while
循环中递增你的计数器,所以它可以退出吗?
答案 1 :(得分:7)
查看循环(或任何其他控制结构)的错误的最佳方法就是运行它。有时你可以在头脑中做到这一点;在其他时候,将跟踪点插入代码可能会有所帮助。
在这种情况下,我认为如果您只是简单地浏览一下代码中的代码,那么您将能够找到它的错误。但出于教学目的,我将在这里完成它。首先让我们为每行代码编号:
$array = array(...); // line 1
$length = 15; // line 2
$counter = 0; // line 3
foreach($array as $values) // line 4
{
$counter++; // line 5
while ($counter <= $length) // line 6
{
// line 7
} // line 8
// line 9
} // line 10
现在让我们来看看它:
$array
被分配了一个单维数组:array(0 => '1', 1 => '2', 2 => '3', ...)
$length
设置为 15 。$counter
是设置 0 。for loop
; $values
= $array[0]
= '1'。$counter
递增。 $counter
= 1 。while loop
;检查$counter
( 1 )&lt; = $length
( 15 )。$counter
( 1 )&lt; = $length
( 15 ),请继续循环。$counter
( 1 )仍然是&lt; = $length
( 15 ),再次进入循环。正如您所看到的,您陷入了无限循环,因为$counter
和$length
都没有更改值。因此,第6行中的while
条件始终求值为 true (1 <= 15)。
答案 2 :(得分:0)
为什么不执行类似下面的代码,它会生成一个循环的密钥。地狱,为什么不做一个生成密钥的功能?
function keyval($length)
{
$length_of_unique_key = $length;
$array = array(
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '!', '£', '$', '%',
'^', '&', '*', '(', ')', '_', '+', '{', '}'
);
for($i=0;$i<$length_of_unique_key;$i++)
{
$key.=$array[rand(0,sizeof($array)-1)];
}
return $key;
}
echo keyval(15);
答案 3 :(得分:0)
你发布的所有代码都是合法的,但很明显你已经遗漏了一些东西,这是帮助解决这个问题的部分...否则,你的$ counter在while循环中保持不变,它永远不会退出