我正在尝试编写一个比较两个数组中的值的程序。用户输入6个存储在数组中的数字。然后我随机创建6个数字并将它们存储在另一个数组中。然后我对数组进行排序并将它们转换为字符串,然后比较字符串以查看两个数组中的值是否相同。如果它们不匹配,在我的while循环中,我尝试随机创建6个数字并将它们存储在第二个数组中,直到数组匹配。然而,当我试图回应所花费的时间时,它只是说' 0' 0倍。
以下是我使用的代码。
<?php
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$number3 = $_POST['number3'];
$number4 = $_POST['number4'];
$number5 = $_POST['number5'];
$number6 = $_POST['number6'];
$userArray = array($number1, $number2, $number3, $number4, $number5, $number6);
// mix and max numbers that can be used with th lottery
$min = 0;
$max = 9;
// random number between 0 and 1 simulating lottery
$lotNumber1 = rand ($min, $max);
$lotNumber2 = rand ($min, $max);
$lotNumber3 = rand ($min, $max);
$lotNumber4 = rand ($min, $max);
$lotNumber5 = rand ($min, $max);
$lotNumber6 = rand ($min, $max);
$lotArray = array($lotNumber1, $lotNumber2, $lotNumber3, $lotNumber4, $lotNumber5, $lotNumber6);
asort($userArray);
asort($lotArray);
$userString = implode($lotArray, "_");
$lotString = implode($lotArray, "_");
$i = 0;
while($lotString != $userString) {
$i ++;
$lotNumber1 = rand ($min, $max);
$lotNumber2 = rand ($min, $max);
$lotNumber3 = rand ($min, $max);
$lotNumber4 = rand ($min, $max);
$lotNumber5 = rand ($min, $max);
$lotNumber6 = rand ($min, $max);
$lotArray = array($lotNumber1, $lotNumber2, $lotNumber3, $lotNumber4, $lotNumber5, $lotNumber6);
asort($lotArray);
$lotString = implode($lotArray, "_");
}
echo "YOU WON it took".$i."times";
?>
答案 0 :(得分:2)
它总是需要零尝试的原因是因为当您最初计算要比较的两个字符串时出现错误!
更改这两行
$userString = implode($lotArray, "_");
$lotString = implode($lotArray, "_");
到
$userString = implode($userArray, "_");
$lotString = implode($lotArray, "_");
这样的事情发生了,不用担心: - )