我需要一次“单击”一次打印一个数组(更具体地说是质数)。我已经创建了素数数组,但我不确定它如何运行,就像用户单击“下一个”按钮,下一个素数出现,然后他单击下一个,另一个素数出现。或者也许有更好的方法来做到这一点?
这是素数数组:
$primes = array();
for ($x = 2; $x <= 1000; $x++) {
$xIsPrime = TRUE;
$sqrtX = sqrt($x);
foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
if ($xIsPrime) echo ($primes[] = $x) . "<br>";
}
最佳答案
这些事情最好用 Javascript 来完成,但是,由于您的问题被标记为 PHP,所以我编写了以下代码:
<?php
$primes = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173);
// Add as many primes as you wish to the array
$num = array_key_exists("hid", $_POST) ? $_POST["hid"]+1 : 0;
?>
<html>
<head>
<!-- Put your meta tags, title, Javascript and CSS here -->
</head>
<body>
<form method="POST">
<h2><?php print($primes[$num]); ?></h2>
<?php
if(sizeof($primes)-$num > 1){
?>
<input type="hidden" name="hid" value="<?php print($num); ?>"/>
<input type="submit" name="sub" value="Next Prime"/>
<?php
}
else{
?>
<input type="submit" name="sub" value="Next Prime" disabled/>
<?php
}
?>
</form>
</body>
</html>
关于php - 如何在php中一次点击打印一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945325/