1
我正在嘗試編寫一個比較兩個數組中的值的程序。用戶輸入存儲在數組中的6個數字。然後我隨機創建6個數字並將它們存儲在另一個數組中。然後,我排序數組並將它們轉換爲字符串,然後比較字符串以查看兩個數組中的值是否相同。如果它們不匹配,在我的while循環中,我嘗試隨機創建6個數字並將它們存儲在第2個數組中,直到數組匹配。然而,當我嘗試回覆所花費的時間時,它只是說'0'次。試圖比較數組中的值PHP
這是我使用的代碼。
<?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";
?>
難道'和array_diff()'是更簡單的方法? – arkascha 2014-10-12 11:27:22